Make Array Strictly Increasing — LeetCode 1187 Python Solution

HardArrayBinary SearchDynamic ProgrammingSorting
Problem
#1187
Reading time
4 min

The problem

Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].

Example

Input
arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
Output
1
Explanation
Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].

Python solution

Python
class Solution:
    def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:
        arr2.sort()
        m = 0
        for x in arr2:
            if m == 0 or x != arr2[m - 1]:
                arr2[m] = x
                m += 1
        arr2 = arr2[:m]
        arr = [-inf] + arr1 + [inf]
        n = len(arr)
        f = [inf] * n
        f[0] = 0
        for i in range(1, n):
            if arr[i - 1] < arr[i]:
                f[i] = f[i - 1]
            j = bisect_left(arr2, arr[i])
            for k in range(1, min(i - 1, j) + 1):
                if arr[i - k - 1] < arr2[j - k]:
                    f[i] = min(f[i], f[i - k - 1] + k)
        return -1 if f[n - 1] >= inf else f[n - 1]

Complexity

MeasureComplexity
Time(n \times (\log m + \min(m, n)))
SpaceO(n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1187. Make Array Strictly Increasing is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1187. Make Array Strictly Increasing?
LeetCode 1187. Make Array Strictly Increasing is rated Hard on LeetCode.
What is the time complexity of LeetCode 1187. Make Array Strictly Increasing?
The Python solution on this page runs in (n \times (\log m + \min(m, n))).
What is the space complexity of LeetCode 1187. Make Array Strictly Increasing?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1187. Make Array Strictly Increasing cover?
LeetCode 1187. Make Array Strictly Increasing is tagged Array, Binary Search, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview