1. Remove-From-List Simulation (Brute Force)
Intuition
To shuffle n elements: copy nums into a dynamic list. In each step, pick a random index in [0, list.size() - 1], append list[index] to the shuffled result, and remove it from the list. Removing from a dynamic list takes O(n), yielding O(n2) time.
When to apply: Use to understand the uniform selection from a shrinking urn of elements.
Urn Removal Shuffle Trace
2 of 2 questions left todayInitial array: [1, 2, 3]
Initial array: [1, 2, 3]. Copy to dynamic urn: [1, 2, 3].
import java.util.*; public class Main { public static class Solution { private int[] original; private Random rand = new Random(); public Solution(int[] nums) { this.original = nums.clone(); } public int[] reset() { return original.clone(); } public int[] shuffle() { List<Integer> list = new ArrayList<>(); for (int x : original) list.add(x); int[] res = new int[original.length]; for (int i = 0; i < res.length; i++) { int idx = rand.nextInt(list.size()); res[i] = list.remove(idx); } return res; } } public static void main(String[] args) { int[] nums = {1, 2, 3}; Solution sol = new Solution(nums); System.out.println("Shuffled: " + Arrays.toString(sol.shuffle())); System.out.println("Reset: " + Arrays.toString(sol.reset())); }}Time & Space Complexity
- Time complexity:
O(n^2) shuffle— n removals, each shifting elements in O(n) time, takes O(n2) total time. - Space complexity:
O(n)— O(n) auxiliary list to hold candidates.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.