Ctrl K

One to the Front, Max to the Back

Easy
You are given an array line of length n that contains every number from 1 to n exactly once, like participants' numbers in a queue that formed in no particular order. In one move you may swap two adjacent elements. Find the smallest number of moves after which 1 stands first in the array and n stands last. The order of everything in between does not matter.
Example 1
line=[3, 1, 2, 4] → 1

A single swap of 3 and 1 is enough: we get [1, 3, 2, 4], with 1 first and 4 last.

Example 2
line=[4, 2, 3, 1] → 5

The 1 has to travel three places left and the 4 three places right, but one of those swaps is between the two of them and counts for both: 5 in total.

Example 3
line=[1, 4, 2, 3, 5] → 0

1 is already first and 5 is already last, so nothing needs to move.

Constraints
  • 2 ≤ n == line.length ≤ 50
  • line contains every number from 1 to n exactly once
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHow Long the Light Stayed On EasyRepack the Tray EasyQuiz Score Log EasyMirror and Negate a Bitmap EasySwap Rows and Columns Easy
loading Python…
Input
line=[3, 1, 2, 4]
Expected
1

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