Make Array Strictly Increasing

Make an array strictly increasing by replacing values with ones from a second array, as few times as possible.

You are given two integer arrays, arr1 and arr2. In one operation you may replace any value of arr1 with any value of arr2, and a value of arr2 can be used any number of times. Return the fewest operations that make arr1 strictly increasing, which means every value is larger than the one before it. If no number of operations can do that, return -1.

Example 1
Input: arr1 = [1, 5, 3, 6, 7], arr2 = [1, 3, 2, 4]
Output: 1
Explanation: replace 5 with 2 to get [1, 2, 3, 6, 7].
Example 2
Input: arr1 = [1, 5, 3, 6, 7], arr2 = [4, 3, 1]
Output: 2
Explanation: replace 5 with 3 and 3 with 4 to get [1, 3, 4, 6, 7].
Example 3
Input: arr1 = [1, 5, 3, 6, 7], arr2 = [1, 6, 3, 3]
Output: -1
Explanation: no set of replacements makes the array strictly increasing.
Solution

The Idea

Think of arr1 as a staircase that must go up at every step: each number has to be larger than the one before it. Some steps are out of place, and arr2 is a box of spare steps you can put in their place. Each replacement counts as one operation, so you want to fix the staircase with as few replacements as possible.

Look at Example 1. In [1, 5, 3, 6, 7] the trouble is 5 followed by 3. Replacing the 3 would need a number above 5 and below 6, and arr2 = [1, 3, 2, 4] has none. Replacing the 5 works: 2 fits between 1 and 3, so one replacement is enough.

Example 2 has the same arr1, but arr2 = [4, 3, 1] has no 2. The 5 can still become 3, but then the old 3 is no longer above the number before it, so it becomes 4. That makes two replacements. Whether to keep the 5 or replace it only became clear at the next number. So how can we decide, number by number, without trying every mix of keeps and replacements?

Notice what the next number cares about. It only has to be larger than the last number placed, so the numbers before that no longer matter. After each number, it is enough to know two things: the last value so far, and how many replacements it took to get there. Let us call that pair a state. If two different ways end in the same last value, we keep the one with fewer replacements.

Look at the picture below. It follows Example 2, one value of arr1 per column, and each box is a state.

States for arr1 = [1, 5, 3, 6, 7] and arr2 = [4, 3, 1]. Keeping 1 gives last 1 with 0 replaced. At 5, keeping gives last 5 with 0 replaced, a dead end, and replacing with 3 gives last 3 with 1 replaced. Then 3 is replaced with 4, and 6 and 7 are kept, for 2 replacements.

We start from nothing yet, with 0 replaced. The 1 can be kept, giving last 1. At the 5 there are two states: keep it for last 5 with 0 replaced, or replace it with 3 for last 3 with 1 replaced. The state last 5 looks cheaper, but it is a dead end. The next value, 3, is not above 5, and arr2 has nothing above 5 to put in its place.

From last 3, the value 3 must be replaced, with 4. After that, 6 and 7 can be kept. The orange boxes in the picture mark this cheapest way through, and it ends with 2 replaced, the answer.

Why replace 5 with 3, and not with 4? A smaller last value is never worse: any number that fits after 4 also fits after 3. So a replacement always takes the smallest value of arr2 that is larger than the last value. With these two rules, the fewest replacements for each last value and the smallest replacement value, we carry a short list of states from one number to the next, instead of trying every mix. Building an answer from the best answers for smaller parts of the problem, here the first few numbers of arr1, is called dynamic programming.

Solution Approach

Turning that idea into code means settling four things: what to remember after each number, which value a replacement uses, how to find that value quickly, and where to start and stop.

What to remember after each number

Why not try every mix of keeps and replacements? Each number can be kept or replaced, so 5 numbers give 32 mixes and 40 numbers give over a trillion. The states avoid that, because many mixes end in the same last value and only the cheapest one is kept.

The states fit in a map from last value to the fewest replacements. How big can it get? A last value is either the number of arr1 just kept or a value of arr2, so with m different values in arr2 the map holds at most m + 1 states.

Which value a replacement uses

From a state with last value last, which value of arr2 should replace the next number? It must be larger than last, and among those, the smallest is best. As with 3 and 4 in Example 2, everything that fits after a bigger value also fits after a smaller one, so the other choices can never lead to fewer replacements.

Finding that value quickly

How do we find the smallest value above last? Scanning all of arr2 works but takes m steps each time. A TreeSet, Java's set that keeps its values sorted, does better. Its method higher(x) returns the smallest value larger than x, or null if there is none, in about log m steps. The set also drops repeated values of arr2.

Where to start and when to stop

What is the state before any number is placed? Its last value must be smaller than every number, so that the first number can always be kept. Integer.MIN_VALUE, the smallest int Java has, plays that part, with 0 replacements.

If at some number no state can keep it and none can replace it, the map ends up empty and the answer is -1. Otherwise, after the last number, the answer is the smallest count among the states left.

Java Solution

The method makeArrayIncreasing works in these steps:

  1. First, put the values of arr2 into a TreeSet named pool, so the smallest value above any number is one higher call away.
  2. Create the map states, from last value to fewest replacements, with one entry: Integer.MIN_VALUE with 0, for nothing placed yet.
  3. A loop takes each value of arr1 in turn as a, and starts an empty map next for the states after it. Inside, a second loop goes over every entry of states, with its last value last and its count ops.
  4. If a is larger than last, keeping it gives the state a with ops. Then replacement = pool.higher(last), and if it exists, replacing gives the state replacement with ops + 1. Both go into next with merge(..., Math::min), which keeps the smaller count when the last value is already there.
  5. After the second loop, if next is empty, return -1. Otherwise next becomes states for the next value.
  6. When all of arr1 is done, return the smallest count in states.

The main method runs the three examples, then [1, 5, 3] where keeping 5 leads to a dead end, [5, 4, 3] where even the first number must be replaced, and [0, 1] with an empty arr2.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;

public class MakeArrayStrictlyIncreasing {

    public static int makeArrayIncreasing(int[] arr1, int[] arr2) {
        TreeSet<Integer> pool = new TreeSet<>();
        for (int v : arr2) {
            pool.add(v);
        }
        // last value of the numbers placed so far -> fewest replacements to get there
        Map<Integer, Integer> states = new HashMap<>();
        states.put(Integer.MIN_VALUE, 0);             // nothing placed yet
        for (int a : arr1) {
            Map<Integer, Integer> next = new HashMap<>();
            for (Map.Entry<Integer, Integer> e : states.entrySet()) {
                int last = e.getKey();
                int ops = e.getValue();
                if (a > last) {
                    next.merge(a, ops, Math::min);    // keep a
                }
                Integer replacement = pool.higher(last);  // smallest value above last
                if (replacement != null) {
                    next.merge(replacement, ops + 1, Math::min);  // replace a
                }
            }
            if (next.isEmpty()) {
                return -1;                            // no way to place a
            }
            states = next;
        }
        int best = Integer.MAX_VALUE;
        for (int ops : states.values()) {
            best = Math.min(best, ops);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(makeArrayIncreasing(new int[] {1, 5, 3, 6, 7}, new int[] {1, 3, 2, 4}));
        System.out.println(makeArrayIncreasing(new int[] {1, 5, 3, 6, 7}, new int[] {4, 3, 1}));
        System.out.println(makeArrayIncreasing(new int[] {1, 5, 3, 6, 7}, new int[] {1, 6, 3, 3}));
        System.out.println(makeArrayIncreasing(new int[] {1, 5, 3}, new int[] {2}));
        System.out.println(makeArrayIncreasing(new int[] {5, 4, 3}, new int[] {1, 2, 3}));
        System.out.println(makeArrayIncreasing(new int[] {0, 1}, new int[] {}));
    }
}

Running it prints:

Output
1
2
-1
1
2
0

The first three lines, 1, 2 and -1, match the examples. Example 3 fails at the 6: by then the only state left is last 6 with 1 replaced, reached by replacing 3 with 6. The 6 is not above 6, and arr2 has nothing larger, so no state survives.

The fourth line is 1 for [1, 5, 3] with arr2 = [2]. Keeping 5 costs nothing at first, but then the 3 has no way forward, so the answer comes from replacing 5 with 2. The fifth line is 2: [5, 4, 3] becomes [1, 2, 3], with the 3 kept.

Look at the last line: 0 for [0, 1], which is already increasing. This is why the start state is Integer.MIN_VALUE and not 0. With a start state of 0, the first 0 cannot be kept, because 0 is not above 0, and the empty arr2 offers no replacement. That version prints -1 for this line.

Complexity

The work is one pass over arr1, and at each number one look at every state.

  • Time: O(n × m × log m), where n is the length of arr1 and m of arr2. Each of the n numbers visits at most m + 1 states, and each visit makes one higher call, about log m steps. Building the TreeSet adds O(m log m) once.
  • Space: O(m). The TreeSet holds at most m values, and each map holds at most m + 1 states.

Keeping only the smallest possible last value is also the key idea in Longest Increasing Subsequence.