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)
- Start by copying the array so you don't mutate the original.
- Loop from the last index down to 1.
- For each index i, pick a random index j between 0 and i (inclusive).
- Swap the elements at indices i and j using destructuring.
Topics
- Utility Functions
Asked at
Google · Spotify · Apple
