Find minimum swaps to sort array with duplicates
Problem Description
You are given an integer array nums of length n, which may contain duplicate values. You are allowed to perform swaps by choosing any two indices i and j and exchanging the values nums[i] and nums[j].
Your task is to determine the minimum number of swaps required to reorder the array nums into non-decreasing order.
Input
The input is a single integer array nums.
Output
The output should be an integer representing the minimum number of swaps needed.
Constraints
1 <= n <= 2 * 10^5-10^9 <= nums[i] <= 10^9
Notes
Due to the presence of duplicate values, there might be multiple valid target arrays that are sorted in non-decreasing order. Your solution must find the minimum number of swaps across all such valid sorted arrangements.
Examples
-
nums = [2, 1, 2]- A sorted form is
[1, 2, 2]. - Answer:
1(e.g., swapnums[0]andnums[1]).
- A sorted form is
-
nums = [1, 5, 1, 5]- A sorted form is
[1, 1, 5, 5]. - Answer:
1(e.g., swapnums[1]andnums[2]to get[1, 1, 5, 5]).
- A sorted form is
AI interview prep
Core dilemma
The central engineering conflict is adapting the standard minimum swaps algorithm (which relies on unique elements and cycle decomposition) to correctly handle duplicates, ensuring that each element is moved to *any* of its valid sorted positions with the minimum total swaps. This involves correctly identifying the 'target' position for each element when multiple identical values exist.
2 tradeoffs and 2 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Find minimum swaps to sort array with duplicates
Problem Description
You are given an integer array nums of length n, which may contain duplicate values. You are allowed to perform swaps by choosing any two indices i and j and exchanging the values nums[i] and nums[j].
Your task is to determine the minimum number of swaps required to reorder the array nums into non-decreasing order.
Input
The input is a single integer array nums.
Output
The output should be an integer representing the minimum number of swaps needed.
Constraints
1 <= n <= 2 * 10^5-10^9 <= nums[i] <= 10^9
Notes
Due to the presence of duplicate values, there might be multiple valid target arrays that are sorted in non-decreasing order. Your solution must find the minimum number of swaps across all such valid sorted arrangements.
Examples
-
nums = [2, 1, 2]- A sorted form is
[1, 2, 2]. - Answer:
1(e.g., swapnums[0]andnums[1]).
- A sorted form is
-
nums = [1, 5, 1, 5]- A sorted form is
[1, 1, 5, 5]. - Answer:
1(e.g., swapnums[1]andnums[2]to get[1, 1, 5, 5]).
- A sorted form is