Find minimum swaps to sort array with duplicates
Akuna CapitalData Scientist · Online AssessmentLast updated
This question evaluates array manipulation and permutation-based reasoning for minimizing swap operations, including handling of duplicate values and performance considerations, within the Coding & Algorithms domain for a Data Scientist role.
Problem
Given an integer array nums of length n that may contain duplicate values, you may perform swaps where you choose any two indices i and j and swap nums[i] and nums[j].
Return the minimum number of swaps required to reorder nums into non-decreasing order.
Input
- An integer array
nums.
Output
- An integer: the minimum number of swaps needed to make
numssorted in non-decreasing order.
Constraints
1 <= n <= 2 * 10^5-10^9 <= nums[i] <= 10^9
Notes
- Because duplicates exist, there can be multiple valid sorted targets; your answer should be the minimum swaps over all valid ways to reach a sorted array.
Examples
nums = [2, 1, 2]→ sorted form is[1, 2, 2], answer1(swap indices 0 and 1).nums = [1, 5, 1, 5]→ answer1(swap the two middle elements to get[1,1,5,5]).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.