Minimum Swaps To Make Sequences Increasing — LeetCode 801 Python Solution

HardArrayDynamic Programming
Problem
#801
Reading time
2 min

The 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].

Example

Input
nums1 = [1,3,5,4], nums2 = [1,2,3,7]
Output
1
Explanation
Swap nums1[3] and nums2[3]. Then the sequences are:

Python solution

Python
class Solution:
    def minSwap(self, nums1: List[int], nums2: List[int]) -> int:
        a, b = 0, 1
        for i in range(1, len(nums1)):
            x, y = a, b
            if nums1[i - 1] >= nums1[i] or nums2[i - 1] >= nums2[i]:
                a, b = y, x + 1
            else:
                b = y + 1
                if nums1[i - 1] < nums2[i] and nums2[i - 1] < nums1[i]:
                    a, b = min(a, y), min(b, x + 1)
        return min(a, b)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 801. Minimum Swaps To Make Sequences Increasing is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 801. Minimum Swaps To Make Sequences Increasing?
LeetCode 801. Minimum Swaps To Make Sequences Increasing is rated Hard on LeetCode.
What is the time complexity of LeetCode 801. Minimum Swaps To Make Sequences Increasing?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 801. Minimum Swaps To Make Sequences Increasing?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 801. Minimum Swaps To Make Sequences Increasing cover?
LeetCode 801. Minimum Swaps To Make Sequences Increasing is tagged Array and Dynamic Programming 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