Minimum Adjacent Swaps to Make a Valid Array — LeetCode 2340 Python Solution

MediumLeetCode PremiumGreedyArray
Problem
#2340
Pattern
Greedy
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. Swaps of adjacent elements are able to be performed on nums.

Example

Input
nums = [3,4,5,5,3,1]
Output
6
Explanation
Perform the following swaps:

Python solution

Python
class Solution:
    def minimumSwaps(self, nums: List[int]) -> int:
        i = j = 0
        for k, v in enumerate(nums):
            if v < nums[i] or (v == nums[i] and k < i):
                i = k
            if v >= nums[j] or (v == nums[j] and k > j):
                j = k
        return 0 if i == j else i + len(nums) - 1 - j - (i > j)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array?
LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array?
The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array cover?
LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array is tagged Greedy and Array on LeetCode.
Is LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array a premium problem?
Yes. LeetCode 2340. Minimum Adjacent Swaps to Make a Valid Array is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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