Skip to the code
cf.
+50 XP

#89 Undo a Recorded Shuffle

hard

A playlist was shuffled with this exact Fisher-Yates procedure: for i from the last index down to 1, take the next random number r from randoms, set j = Math.floor(r * (i + 1)), and swap the songs at i and j. The app saved the random numbers and the shuffled result, shuffled.

Write undoShuffle(shuffled, randoms) that returns the playlist in its original order.

Example 1

Input: shuffled = ["q2","q1","q4","q3"], randoms = [0.5,0.9,0.1]
Output: ["q1","q2","q3","q4"]

The swaps were (3, 2), (2, 2), (1, 0). Undoing them in reverse order ((1, 0), then (2, 2), then (3, 2)) gives back the original.

Example 2

Input: shuffled = ["x"], randoms = []
Output: ["x"]

Nothing was swapped.

Constraints

  • 0 <= shuffled.length <= 10^4
  • randoms.length === Math.max(0, shuffled.length - 1)
  • 0 <= randoms[i] < 1
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).