Minimum Swaps To Make Sequences Increasing - Problem

You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].

For example, if nums1 = [1,2,3,8] and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].

Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.

An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,3,5,4], nums2 = [1,2,3,7]
Output: 1
💡 Note: Swap nums1[3] and nums2[3] to get nums1 = [1,3,5,7] and nums2 = [1,2,3,4]. Both arrays become strictly increasing with 1 swap.
Example 2 — No Swaps Needed
$ Input: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]
Output: 1
💡 Note: Need to swap at position 1 to make both sequences strictly increasing: nums1 = [0,1,5,8,9], nums2 = [2,3,4,6,9].
Example 3 — Multiple Valid Solutions
$ Input: nums1 = [1,2], nums2 = [3,4]
Output: 0
💡 Note: Both arrays are already strictly increasing, so no swaps needed.

Constraints

  • 2 ≤ nums1.length == nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 2000

Visualization

Tap to expand
Minimum Swaps To Make Sequences Increasing INPUT nums1: 1 3 5 4 Index: 0 1 2 3 nums2: 1 2 3 7 Index: 0 1 2 3 Problem at index 3: nums1[3]=4 not greater than nums1[2]=5 swap? ALGORITHM STEPS 1 Define DP States keep[i]: min swaps if no swap at i swap[i]: min swaps if swap at i 2 Initialize keep[0] = 0, swap[0] = 1 3 Transition Rules If naturally increasing: keep[i] = keep[i-1] swap[i] = swap[i-1] + 1 If swappable: keep[i] = min(keep[i], swap[i-1]) swap[i] = min(swap[i], keep[i-1]+1) 4 Return Result min(keep[n-1], swap[n-1]) DP Table: i: 0 1 2 3 keep: 0 0 0 1 swap: 1 1 1 1 FINAL RESULT After swapping at index 3: nums1 (new): 1 3 5 7 nums2 (new): 1 2 3 4 Verification: nums1: 1 < 3 < 5 < 7 [OK] nums2: 1 < 2 < 3 < 4 [OK] OUTPUT 1 Key Insight: At each position, we track two states: minimum swaps needed if we keep the current elements vs if we swap them. The DP transition considers whether elements are naturally ordered or can be fixed by swapping. Time: O(n) | Space: O(1) using only previous state variables instead of full arrays. TutorialsPoint - Minimum Swaps To Make Sequences Increasing | Optimal DP Solution
Asked in
Google 15 Facebook 12 Amazon 8
32.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen