Algorithm to print out a shuffled list, in-place and with O1 memory
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Shuffling a list in-place with memory is a fundamental computer science problem often encountered in various fields such as data analysis, game development, and more. The challenge is to rearrange a list of elements randomly without using extra space. One of the most popular algorithms to achieve this is the Fisher-Yates Shuffle, also known as the Knuth Shuffle.
The Fisher-Yates Shuffle
The Fisher-Yates Shuffle is a simple yet elegant algorithm that provides an unbiased shuffle of elements. Here is a step-by-step breakdown of how it works:
Algorithm Explanation
- Start with the last element: Consider the list of
nelements and start with then-thelement. - Randomly generate an index: For the current element at index
i, randomly select another index between0andi(inclusive). - Swap elements: Swap the elements at indices
iand the randomly generated index. - Move to the next element: Decrement the index to move to the previous element and repeat the process until the index is
0.
This algorithm works because by repeatedly choosing a random position for each element from a shrinking pool of possibilities, it ensures all permutations of the list are equally likely.
Pseudocode Implementation
Below is the pseudocode for the algorithm:
- Time Complexity: The time complexity is because each element in the list is examined exactly once.
- Space Complexity: As mentioned, the space complexity is due to the constant number of extra variables required.
- Gaming: For randomly shuffling cards in card games.
- Simulations: To randomize data samples in simulations to avoid bias.
- Cryptography: In certain cryptographic protocols where unbiased randomness is required.
- The naive approach, which often involves selecting a random element to place at the end repeatedly, results in biased outcomes and inefficient time complexity.

