Ctrl K

Shortest Left, Tallest Right

Medium
Students stand in a row and their heights are listed in heights. In one step you may swap two **neighbouring** students. The photographer wants the shortest student at the left end and the tallest at the right end. If several students share the smallest or the largest height, any one of them may take that end. The order of everyone else does not matter. Return the minimum number of swaps needed.
Example 1
heights=[4, 7, 2, 7, 5] → 3

Move the 2 to the front in 2 swaps: [2, 4, 7, 7, 5]. Then the last 7 to the end in 1 swap: [2, 4, 7, 5, 7]. 3 in total.

Example 2
heights=[3, 1] → 1

One swap gives [1, 3]: the minimum is on the left and the maximum on the right.

Example 3
heights=[5, 5, 5] → 0

All values are equal, so each is both a smallest and a largest one. No swaps are needed.

Constraints
  • 1 ≤ heights.length ≤ 10⁵
  • 1 ≤ heights[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumWhere to Start the Lap Medium
loading Python…
Input
heights=[4, 7, 2, 7, 5]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.