Similar Problems
Similar Problems not available
Make Array Strictly Increasing - Leetcode Solution
Companies:
LeetCode: Make Array Strictly Increasing Leetcode Solution
Difficulty: Hard
Topics: sorting dynamic-programming binary-search array
Problem Statement: Given two arrays arr1 and arr2, you have to convert arr1 into a strictly increasing array such that all its elements are distinct and arr1[i] > arr1[i-1]. In a single operation, you can choose any index i where 0 <= i < arr1.length and change arr1[i] to any integer. Additionally, you have to ensure that the resulting array arr1 is such that arr1[i] > arr2[i] for all 0 <= i < arr1.length.
Solution: The problem statement states that we need to change the original array arr1 such that it is strictly increasing, and arr1[i] > arr2[i] for all i.
We can solve this problem by using dynamic programming. Let's define a 2D array dp, where dp[i][j] is the minimum number of operations needed to make the first i elements of arr1 strictly increasing, and the ith element is arr1[i-1], and the jth element of arr2 is arr2[j-1].
We can use the following recurrence relation to fill the dp array:
if arr1[i-1] > arr1[i-2] and arr1[i-1] > arr2[j-1]: dp[i][j] = dp[i-1][j] if arr1[i-1] > arr1[i-2] and arr1[i-1] <= arr2[j-1]: dp[i][j] = min(dp[i][j], dp[i-1][j] + 1) if arr1[i-1] <= arr1[i-2] and arr1[i-1] > arr2[j-1]: dp[i][j] = min(dp[i][j], dp[i-1][j-1]) if arr1[i-1] <= arr1[i-2] and arr1[i-1] <= arr2[j-1]: dp[i][j] = inf
Where inf denotes a very large number, and dp[0][j] = 0 for all j.
The first case denotes that we do not have to change the ith element of arr1 if it is already strictly increasing and greater than arr2[j-1]. Thus, we can copy the minimum operations needed from the previous index, dp[i-1][j].
The second case denotes that we can change the ith element of arr1 to any number greater than arr1[i-2], and less than or equal to arr2[j-1], and add 1 to the minimum operations needed to make the first i elements strictly increasing.
The third case denotes that we can change the ith element of arr1 to any number greater than arr2[j-1], and the jth element of arr2 is not used in the current index, thus we can copy the minimum operations needed from dp[i-1][j-1].
The fourth case denotes that there is no way to make the ith element of arr1 strictly increasing and greater than arr2[j-1], thus we can set dp[i][j] to inf.
Finally, the minimum operations needed to make the entire array arr1 strictly increasing and greater than arr2 can be found by taking the minimum of dp[n][j], for all j.
Thus, the time complexity of our solution is O(nm), where n is the length of arr1, and m is the length of arr2, and the space complexity is also O(nm) for the dp array.
Code:
Make Array Strictly Increasing Solution Code
1