The Random Flip Matrix problem asks you to design a class that randomly flips a 0-entry in an m×n binary matrix (initially all zeros) to 1, uniformly at random among all remaining zeros. It must support reset to all zeros. This coding problem uses virtual index mapping to avoid O(mn) space. The math, hash table, reservoir sampling, and randomized interview pattern is demonstrated.
Google asks this to test space-efficient random sampling. The naive approach stores all zero positions in a list; the elegant solution uses a hash map to virtually rearrange remaining indices, similar to Fisher-Yates shuffle without materializing the full array.
Fisher-Yates shuffle with hash map. Maintain remaining = total zeros = m*n. For each flip: pick a random index r in [0, remaining-1]. Map r to an actual (row, col) pair using r → map.get(r, r). Record the flipped position. Swap this slot with the last slot: map[r] = map.get(remaining-1, remaining-1). Decrement remaining.
m=2, n=3. Total=6. Map starts empty.
Random Flip Matrix teaches the "virtual Fisher-Yates" technique: sample from a shrinking range without materializing all elements. The hash map stores only elements that have been remapped. This approach is O(1) space (excluding hash map entries) per operation. Practice: "random sampling without replacement," "reservoir sampling for k elements." Virtual array techniques are essential for memory-constrained random sampling.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Random Pick Index | Medium | Solve | |
| Linked List Random Node | Medium | Solve | |
| Smallest Integer Divisible by K | Medium | Solve | |
| Insert Delete GetRandom O(1) | Medium | Solve | |
| Insert Delete GetRandom O(1) | Medium | Solve |