As reported: Warner Bros. Discovery in-person hiring drive (Bangalore), February 2026, round 1: the second of two DSA questions, both solved — find the minimum number of swaps to sort an array.
Given an array nums of distinct integers, return the minimum number of swaps needed to sort it in ascending order. A swap exchanges any two elements (they do not have to be adjacent).
Example 1
nums = [4,3,2,1]
Output: 2
Swap 4 and 1, then 3 and 2.
Example 2
nums = [1,5,4,3,2]
Output: 2
Swap 5 and 2 → [1,2,4,3,5], then 4 and 3.
Example 3
nums = [10,19,6,3,5]
Output: 2
Constraints: 1 <= nums.length <= 10^5, -10^9 <= nums[i] <= 10^9, all values are distinct.
Code runner format: one JSON value per line: nums. Implement minSwaps(nums) returning an integer.
Clarifications
- Any two positions may be swapped (if only adjacent swaps were allowed, the answer would be the number of inversions instead).