Make Array Strictly Increasing (LeetCode 1187): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Sort
arr2and remove duplicates so that binary search finds the next larger value. - Define
dp(i, prev), the fewest operations to makearr1[i:]strictly increasing after a previous valueprev. Return 0 whenireaches the end. - If
arr1[i] > prev, one option is to keep it:dp(i + 1, arr1[i]). - Find
idx = bisect_right(arr2, prev). If it is in range, another option is1 + dp(i + 1, arr2[idx]), replacing with the smallest larger value. - Return the smaller option, or infinity if neither applies.
- 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]
- Sorted unique
arr2is [1, 2, 3, 4]. dp(0, -1): keeping 1 leads todp(1, 1). Replacing with 1 costs 1 and also leads todp(1, 1), so keeping is better.dp(1, 1): keeping 5 leads todp(2, 5), but 3 is not greater than 5 and no value inarr2exceeds 5, so that branch is infinity.- 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, sodp(2, 2) = 0. - So
dp(1, 1) = 1and 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 -11class Solution {
2 int[] arr1, arr2;
3 Map<Long, Integer> memo = new HashMap<>();
4
5 public int makeArrayIncreasing(int[] arr1, int[] arr2) {
6 this.arr1 = arr1;
7 TreeSet<Integer> set = new TreeSet<>();
8 for (int x : arr2) set.add(x);
9 this.arr2 = set.stream().mapToInt(i -> i).toArray();
10
11 int ans = dp(0, -1);
12 return ans >= 1e9 ? -1 : ans;
13 }
14
15 private int dp(int i, int prev) {
16 if (i == arr1.length) return 0;
17
18 long key = (long) i * 2000001 + prev + 1;
19 if (memo.containsKey(key)) return memo.get(key);
20
21 int result = (int) 1e9;
22
23 if (arr1[i] > prev) {
24 result = dp(i + 1, arr1[i]);
25 }
26
27 int idx = upperBound(arr2, prev);
28 if (idx < arr2.length) {
29 result = Math.min(result, 1 + dp(i + 1, arr2[idx]));
30 }
31
32 memo.put(key, result);
33 return result;
34 }
35
36 private int upperBound(int[] arr, int val) {
37 int lo = 0, hi = arr.length;
38 while (lo < hi) {
39 int mid = (lo + hi) / 2;
40 if (arr[mid] <= val) lo = mid + 1;
41 else hi = mid;
42 }
43 return lo;
44 }
45}1class Solution {
2public:
3 vector<int> arr2Sorted;
4 map<pair<int, int>, int> memo;
5
6 int makeArrayIncreasing(vector<int>& arr1, vector<int>& arr2) {
7 set<int> s(arr2.begin(), arr2.end());
8 arr2Sorted = vector<int>(s.begin(), s.end());
9
10 int ans = dp(arr1, 0, -1);
11 return ans >= 1e9 ? -1 : ans;
12 }
13
14 int dp(vector<int>& arr1, int i, int prev) {
15 if (i == arr1.size()) return 0;
16
17 auto key = make_pair(i, prev);
18 if (memo.count(key)) return memo[key];
19
20 int result = 1e9;
21
22 if (arr1[i] > prev) {
23 result = dp(arr1, i + 1, arr1[i]);
24 }
25
26 auto it = upper_bound(arr2Sorted.begin(), arr2Sorted.end(), prev);
27 if (it != arr2Sorted.end()) {
28 result = min(result, 1 + dp(arr1, i + 1, *it));
29 }
30
31 return memo[key] = result;
32 }
33};Time and space complexity
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.
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_leftinstead ofbisect_right, which can pick a replacement equal toprevand break the strict inequality. - Trying every value in
arr2as 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.