#1187

Make Array Strictly Increasing

Hard
ArrayBinary SearchDynamic ProgrammingSortingDynamic ProgrammingSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n)
💡

Intuition

Time O(n * m)Space O(n)

The optimal approach uses dynamic programming to efficiently track the minimum operations needed to make arr1 strictly increasing by leveraging sorted arr2. We maintain a state that considers the last used element from arr2 to ensure we can build a strictly increasing sequence.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort arr2 and remove duplicates to simplify replacements.
  2. 2Step 2: Initialize a DP array where dp[i] represents the minimum operations needed to make arr1[0..i] strictly increasing.
  3. 3Step 3: For each element in arr1, check against all elements in arr2 to find valid replacements that maintain the strictly increasing order.
  4. 4Step 4: Update the DP array based on the minimum operations found.
solution.py16 lines
1# Full working Python code
2import bisect
3
4def min_operations(arr1, arr2):
5    arr2 = sorted(set(arr2))
6    n = len(arr1)
7    dp = [float('inf')] * (n + 1)
8    dp[0] = 0  # No operations needed for an empty array
9
10    for i in range(1, n + 1):
11        for j in range(len(arr2)):
12            if arr2[j] > (arr1[i - 1] if i > 1 else float('-inf')):
13                dp[i] = min(dp[i], dp[i - 1])
14            if j > 0 and arr2[j] > arr1[i - 1]:
15                dp[i] = min(dp[i], dp[i - 1] + 1)
16    return dp[n] if dp[n] != float('inf') else -1

Complexity note: The time complexity is O(n * m) where n is the length of arr1 and m is the length of arr2. This is due to the nested loops iterating through arr1 and arr2.

  • 1Dynamic programming can reduce the complexity of problems involving sequences.
  • 2Sorting and removing duplicates can simplify the problem space.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.