Make Array Strictly Increasing (LeetCode 1187): Solution and Explanation

Hard
Array
Binary Search
Dynamic Programming

You have two integer arrays. In one operation you can overwrite any element of the first array with any element of the second. Return the fewest operations that make the first array strictly increasing, or -1 if it cannot be done.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Walk through arr1 from left to right. At each position, the only thing that matters about the past is the value we ended up with at the previous position, because the current element must be strictly larger than it. Which earlier elements we replaced, and with what, no longer matters. That gives a clean state: (i, prev), the index we are deciding and the value just before it.

At each state there are two choices. We can keep arr1[i] if it is greater than prev, at no cost. Or we can replace it with some value from arr2 that is greater than prev, at a cost of one. Among all valid replacements, the smallest one is always the best choice: a smaller value at position i leaves more room for every later element, so anything achievable after a larger replacement is also achievable after the smallest one. That greedy observation means each state has at most two branches instead of len(arr2).

Sorting arr2 and removing duplicates lets us find that smallest valid replacement with one bisect_right, the first value strictly greater than prev. Memoizing on (i, prev) keeps the search polynomial, since prev can only be -1, a value from arr1 or a value from arr2. If neither branch works at some position, the state returns infinity, and an infinite final answer means the task is impossible.

Approach: Memoized DP with binary search for replacements

  1. Sort arr2 and remove duplicates so that binary search finds the next larger value.
  2. Define dp(i, prev), the fewest operations to make arr1[i:] strictly increasing after a previous value prev. Return 0 when i reaches the end.
  3. If arr1[i] > prev, one option is to keep it: dp(i + 1, arr1[i]).
  4. Find idx = bisect_right(arr2, prev). If it is in range, another option is 1 + dp(i + 1, arr2[idx]), replacing with the smallest larger value.
  5. Return the smaller option, or infinity if neither applies.
  6. Call dp(0, -1) and return -1 if the result is infinity.

Step-by-step example

arr1 = [1, 5, 3, 6, 7], arr2 = [1, 3, 2, 4]
  1. Sorted unique arr2 is [1, 2, 3, 4].
  2. dp(0, -1): keeping 1 leads to dp(1, 1). Replacing with 1 costs 1 and also leads to dp(1, 1), so keeping is better.
  3. dp(1, 1): keeping 5 leads to dp(2, 5), but 3 is not greater than 5 and no value in arr2 exceeds 5, so that branch is infinity.
  4. Replacing 5 with 2 (the first value above 1) costs 1 and leads to dp(2, 2). From there 3, 6 and 7 can all be kept, so dp(2, 2) = 0.
  5. So dp(1, 1) = 1 and the final answer is 1: replace 5 with 2 to get [1, 2, 3, 6, 7].

Code: Python, Java, C++

1class Solution:
2    def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:
3        arr2 = sorted(set(arr2))
4
5        @lru_cache(maxsize=None)
6        def dp(i, prev):
7            if i == len(arr1):
8                return 0
9
10            result = float('inf')
11
12            # Option 1: Keep arr1[i] if valid
13            if arr1[i] > prev:
14                result = dp(i + 1, arr1[i])
15
16            # Option 2: Replace with smallest valid from arr2
17            idx = bisect.bisect_right(arr2, prev)
18            if idx < len(arr2):
19                result = min(result, 1 + dp(i + 1, arr2[idx]))
20
21            return result
22
23        ans = dp(0, -1)
24        return ans if ans != float('inf') else -1

Time and space complexity

Time

O(n log n + m × (m + n) × log n)

With m = len(arr1) and n = len(arr2), sorting costs O(n log n). The prev value comes from at most m + n + 1 distinct values, giving O(m × (m + n)) states, and each does one binary search.

Space

O(m × (m + n))

The memo cache holds one entry per reachable (i, prev) pair, plus recursion depth m.

Other approaches

DP keyed by number of operations (time O(m × min(m, n) × log n), space O(min(m, n)))

Keep a map from the number of replacements used so far to the smallest possible last value. For each position, build a new map by either keeping arr1[i] or replacing it with the next larger value from arr2. The answer is the smallest key that survives to the end. It avoids recursion and is often faster.

Common mistakes

  • Using bisect_left instead of bisect_right, which can pick a replacement equal to prev and break the strict inequality.
  • Trying every value in arr2 as a replacement instead of only the smallest valid one, which multiplies the work by n.
  • Greedily keeping arr1[i] whenever it is valid. Sometimes replacing a large valid value with a smaller one is what makes later positions work.
  • Starting with prev = 0, which wrongly forbids a first element of 0. Use a value below every allowed number, such as -1.

Frequently asked questions

Why is it enough to try only the smallest larger value from arr2?

Any larger replacement leaves less room for the rest of the array. Whatever sequence of choices works after a larger value also works after the smallest one, so the smallest is never worse.

Why can't a greedy solution decide when to replace?

Keeping a valid but large element may block later positions, while replacing it costs one now but saves several replacements later. Only by comparing both branches can we be sure of the minimum.

When does Make Array Strictly Increasing return -1?

When some position cannot be made larger than the previous value, either by keeping it or by any element of arr2, along every possible choice of earlier operations.