Fisher-Yates Shuffle

MediumUtility Functions10 min4 tests

Implement a shuffle function using the Fisher-Yates algorithm to randomly reorder elements in an array.

Requirements

  • Return a new shuffled array (do not mutate the original)
  • Every element from the input must appear exactly once in the output
  • Use the Fisher-Yates (Knuth) shuffle algorithm
  • Iterate from the end, swapping each element with a random earlier element

Example

shuffle([1, 2, 3, 4, 5]); // e.g., [3, 1, 5, 2, 4]
Hints (4)
  1. Start by copying the array so you don't mutate the original.
  2. Loop from the last index down to 1.
  3. For each index i, pick a random index j between 0 and i (inclusive).
  4. Swap the elements at indices i and j using destructuring.

Topics

  • Utility Functions

Asked at

Google · Spotify · Apple

Join Us
blur