1. Expanded Frequency Array (Brute Force)
Intuition
If w = [1, 3], create an array of size 1 + 3 = 4: [0, 1, 1, 1]. Picking uniformly at random from this expanded array yields index 0 with probability 1/4 and index 1 with probability 3/4. This is memory-prohibitive when weights are large.
When to apply: Use for tiny weights sum to understand the exact discrete probability distribution.
Expanded Roulette Array (O(Sum(W)) Space)
2 of 2 questions left todayDirect expansion models probability through duplication
Direct expansion models probability through duplication.
import java.util.*; public class Main { public static class Solution { private List<Integer> list = new ArrayList<>(); private Random rand = new Random(); public Solution(int[] w) { for (int i = 0; i < w.length; i++) { for (int count = 0; count < w[i]; count++) { list.add(i); } } } public int pickIndex() { return list.get(rand.nextInt(list.size())); } } public static void main(String[] args) { int[] w = {1, 3}; Solution sol = new Solution(w); System.out.println("Random Pick: " + sol.pickIndex()); }}Time & Space Complexity
- Time complexity:
O(sum(w)) space, O(1) pick— Building the expanded array takes time proportional to the sum of weights. - Space complexity:
O(sum(w))— Stores sum(w) entries, which exceeds memory when weights sum to 109.
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.