Skip to solution
mediumDSA

Implement Fisher-Yates Shuffle (in-place, unbiased)

854 views
01

Understand the problem

Create shuffle(array) that returns a uniformly random permutation in O(n) without bias. Do not use sort with Math.random.

arrayshufflefisher-yates
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Approach: Iterate from end, swap i with random j in [0,i]. Copy first to avoid mutating input.

function shuffle(array) {
  const a = [...array];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

// D

Solution ready — 2 min read

Classified // press E to declassify

04

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 123 of 190 decoded in the JavaScript Coding track. One more won't hurt.

Back to track