Math Fundamentals18 sections · 814 units
Open in Course

Shuffle - Implementation

The code

Here's the complete solution:


class Solution
    original := copy of input array
    current := copy of input array

    function reset()
        current := copy of original
        return current

    function shuffle()
        n := length of current
        for i from 0 to n - 1
            // Pick random index from i to n-1
            j := random integer in range [i, n-1]
            // Swap elements at i and j
            swap current[i] and current[j]
        return current

Time: O(n)O(n) per shuffle (single pass), Space: O(n)O(n) to store the original array. The random swap at each position guarantees fairness.