1371. Slider Swaps to Order

Medium3.5 points estimatedSortingGreedyGraphArray

A tile puzzle has n tiles in a row, numbered 1 to n and shuffled into the array perm. The tile numbered 1 is the blank slot. The only legal move swaps the blank with any other tile, at any distance.

The puzzle is solved when perm[i] == i + 1 for every index i, so the blank ends in the first position. Return the minimum number of moves needed to reach the solved row, or 0 if it is already solved. Follow the cycles of the permutation: a cycle of length L at least 2 that contains the blank is fixed in L - 1 moves, while any other cycle needs L + 1 moves because the blank has to visit it. Aim for O(n) time and O(n) space.

Example 1

Input:
perm = [2,1,3]
Output:
1
Explanation:

The blank (tile 1) sits in the second slot; swapping it with tile 2 gives [1, 2, 3] in one move.

Example 2

Input:
perm = [1,2,3,4]
Output:
0
Explanation:

The row is already solved, so zero moves are needed.

Example 3

Input:
perm = [1,3,2]
Output:
3
Explanation:

The blank is home, but tiles 2 and 3 are swapped; the blank swaps with 3, then with 2, then with 3 again, giving 3 moves.

Constraints

  • 1 ≤ perm.length ≤ 105

  • perm is a permutation of the integers 1 to n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…