A robot arm tidies a library shelf. The shelf holds books numbered 1 to n, each exactly once, in some shuffled order. In one move, the arm picks any two slots and swaps their books. The shelf is tidy when slot i (0-based) holds book i + 1.
Write two functions that take the array shelf:
minSwaps(shelf) returns the fewest swaps needed to tidy the shelf.
swapPlan(shelf) returns a list of [i, j] slot pairs, with i < j, that tidies the shelf when the swaps are applied in order, using exactly minSwaps(shelf) swaps. Any such plan is accepted. It must not modify shelf.
Rules:
An empty shelf needs 0 swaps and the plan [].
If shelf is not an array containing each of the integers 1 to n exactly once, throw a TypeError.
Shelves can hold 200,000 books. Looking up where each book is with indexOf, as a selection sort does, is quadratic and will not finish in time.
minSwaps([4, 3, 1, 2]); // 3: one cycle 0 → 3 → 1 → 2 → 0 of length 4minSwaps([2, 1, 4, 3]); // 2: two cycles of length 2minSwaps([1, 2, 3]); // 0swapPlan([2, 3, 1]); // for example [[0, 1], [0, 2]]: [2,3,1] → [3,2,1] → [1,2,3]
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.