Minimum Swaps To Make Sequences Increasing - Problem

You're given two integer arrays of the same length, nums1 and nums2. Your mission is to make both arrays strictly increasing using the minimum number of swap operations.

In one operation, you can swap nums1[i] with nums2[i] at any position i. For example:

  • If nums1 = [1,2,3,8] and nums2 = [5,6,7,4]
  • Swapping at index 3 gives us nums1 = [1,2,3,4] and nums2 = [5,6,7,8]

Goal: Return the minimum number of swaps needed to make both arrays strictly increasing.

Note: An array is strictly increasing if each element is greater than the previous one: arr[0] < arr[1] < arr[2] < ...

โœ… Guaranteed: The input always has a valid solution!

Input & Output

example_1.py โ€” 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 are now strictly increasing with just 1 swap.
example_2.py โ€” No Swaps Needed
$ Input: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]
โ€บ Output: 1
๐Ÿ’ก Note: After 1 swap at position 1: nums1=[0,1,5,8,9], nums2=[2,3,4,6,9]. Both sequences become strictly increasing.
example_3.py โ€” Multiple Swaps
$ Input: nums1 = [1,3,5,4], nums2 = [1,2,3,7]
โ€บ Output: 1
๐Ÿ’ก Note: Only need to swap at position 3 to make both arrays strictly increasing: nums1=[1,3,5,7], nums2=[1,2,3,4].

Constraints

  • 2 โ‰ค nums1.length โ‰ค 105
  • nums2.length == nums1.length
  • 0 โ‰ค nums1[i], nums2[i] โ‰ค 2 ร— 105
  • The test cases are generated so that the given input always makes it possible

Visualization

Tap to expand
๐ŸŽผ Orchestra Conductor's Dynamic StrategyMusicians with Number Cards13546Row 1 (nums1)12374Row 2 (nums2)SWAPConductor's Decision Process:Position 0: Start with keep=0, swap=1Position 1: Check if natural order (1<3, 1<2) โœ“ โ†’ keep=0, swap=2Position 2: Check if natural order (3<5, 2<3) โœ“ โ†’ keep=0, swap=3Position 3: Natural order fails (5>4) โœ—, but cross order works โœ“โ†’ keep=3, swap=1 (swap here if we kept before, or keep if we swapped)๐ŸŽฏ Final ResultMinimum Swaps = 1Swap positions 3: [1,3,5,7] and [1,2,3,4]
Understanding the Visualization
1
Set Initial States
Position 0: keep=0 swaps, swap=1 swap
2
Check Valid Transitions
For each position, see which previous states allow increasing order
3
Update Optimally
Choose the path with minimum swaps that maintains the increasing constraint
4
Return Best Final State
The answer is the minimum of keep and swap at the last position
Key Takeaway
๐ŸŽฏ Key Insight: Dynamic Programming tracks optimal states at each position, making locally optimal decisions that lead to the globally optimal solution with O(n) efficiency.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
89.1K Views
Medium Frequency
~25 min Avg. Time
1.8K 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