KatInterview

Is This Playlist Shuffle Actually Fair?

Statistics & ExperimentsModel answer
MediumModel answerStatistics & Experimentsprobabilityshufflealgorithm-analysis

Last updated

Determine whether a naive shuffle that always picks from the full array produces a uniform distribution, and explain why or why not using probability theory.

Background

A junior engineer on your team built a playlist shuffler. Rather than using the textbook approach, they wrote their own version:

def playlist_shuffle(arr):
    n = len(arr)
    for i in range(n):
        # Swap element i with any position in the full array
        j = random.randint(0, n - 1)
        arr[i], arr[j] = arr[j], arr[i]
    return arr

You're asked to audit this implementation before it ships.

Your Tasks

  1. Probability Analysis: Does this algorithm generate each possible ordering with equal probability? Construct a mathematical argument. If the distribution is not uniform, explain precisely why.

  2. Complexity: What are the time and space complexities of this function?

  3. RNG Quality: Set the correctness of the algorithm aside for a moment. What practical issues with the underlying random number generator could degrade shuffle quality even further?

  4. Fairness Testing: Propose one or more concrete methods to verify whether any shuffle implementation is statistically unbiased.

Constraints

  • Treat random.randint(a, b) as producing a perfectly uniform integer in [a, b].
  • Use small cases (e.g. n = 3) to build your argument before generalizing.

Worked Example

For the array [A, B, C] (n = 3):

  • Each of the 3 iterations picks independently from 3 positions.
  • There are 3³ = 27 equally likely sequences of choices in total.
  • There are 3! = 6 possible orderings.
  • For the distribution to be uniform, each ordering would need to be produced by exactly 27 / 6 = 4.5 choice sequences.

What does that tell you?

Hints

Hint 1

Count the total number of equally likely execution paths (n^n) and the number of permutations (n!). For the shuffle to be uniform, the first number must divide the second evenly — check whether that's guaranteed.

Hint 2

For n = 3, manually trace a few choice sequences to see which orderings are over-represented and which are under-represented. This concrete enumeration turns the abstract argument into something you can show.

Hint 3

Fisher-Yates avoids this problem by restricting the random draw to the not-yet-finalized portion of the array. Think about how that changes the path-count arithmetic.