Problem
Given distinct weights, count the fewest adjacent swaps needed to put the minimum first and the maximum last. Other weights may appear in any order.
Worked examples
Input: weights = [4, 1, 3, 5, 2]
Output: 2
Move 1 one step left and 5 one step right.
Hints
Hint 1
Only the positions of the minimum and maximum matter.
Hint 2
If the maximum starts before the minimum, one swap helps both movements.
Solution approach
- Find the minimum index i and maximum index j in one scan.
- Add i + (n - 1 - j). Subtract one when j < i because their paths cross.
- Clarify ties if duplicate weights are allowed; this practice version assumes distinct weights.
Python reference implementation
def swaps_to_ends(a):
if not a: return 0
i = min(range(len(a)), key=a.__getitem__)
j = max(range(len(a)), key=a.__getitem__)
return i + len(a) - 1 - j - int(j < i)Complexity
O(n) time and O(1) extra space.
Report & practice notes
Restated practice version with original examples and explanation. The source is a candidate account, not an official question paper; assessment details can vary. Difficulty is our editorial estimate.
Read the candidate’s source report ↗