Minimum Swaps To Make Sequences Increasing — LeetCode 801 Python Solution
- Problem
- #801
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.