Random Flip Matrix
Problem (restated)
An m × n matrix starts all zeros. flip() returns a uniform unused cell [r, c] and marks it used. reset() restores every cell.
Intuition
Treat the matrix as a virtual array of size m*n. Fisher-Yates would swap a random remaining index with the tail, but the array is too large to allocate. Store only the swaps in a hashmap: pick k in [0, remaining), resolve through the map, then map k onto the current tail and shrink.
Approaches
Virtual Fisher-Yates map
UnverifiedIdea. x = map.get(k) ?? k. Last remaining index is remaining-1, also mapped. Write that last value onto k, decrement. Convert x to [x / n, x % n]. reset clears the map and restores remaining = m*n.
Walkthrough. 2×2, remaining=4. Draw 1 → cell [0,1], map 1→3, remaining=3. Draw 1 again → 3 → [1,1]. Unused cells stay 0 and 2.
Trade-offs. A boolean matrix is O(mn) space and O(mn) worst-case to find a zero. The virtual map is O(flipped cells) and O(1) per flip.
export class Solution {
private m: number;
private n: number;
private remaining: number;
private map: Map<number, number>;
constructor(m: number, n: number) {
this.m = m;
this.n = n;
this.remaining = m * n;
this.map = new Map();
}
flip(): number[] {
const k = Math.floor(Math.random() * this.remaining);
this.remaining--;
const x = this.map.get(k) ?? k;
const last = this.map.get(this.remaining) ?? this.remaining;
this.map.set(k, last);
return [Math.floor(x / this.n), x % this.n];
}
reset(): void {
this.map.clear();
this.remaining = this.m * this.n;
}
}
export class Solution {
private m: number;
private n: number;
private remaining: number;
private map: Map<number, number>;
constructor(m: number, n: number) {
this.m = m;
this.n = n;
this.remaining = m * n;
this.map = new Map();
}
flip(): number[] {
const k = Math.floor(Math.random() * this.remaining);
this.remaining--;
const x = this.map.get(k) ?? k;
const last = this.map.get(this.remaining) ?? this.remaining;
this.map.set(k, last);
return [Math.floor(x / this.n), x % this.n];
}
reset(): void {
this.map.clear();
this.remaining = this.m * this.n;
}
}
Template connection
Rejection / blacklist on the Reservoir Sampling page: a uniform draw in a shrinking prefix, remapped around already-used indices; Fisher-Yates with a sparse array.
Reflection
- Draw
kin[0, remaining). If the map holdsk, use that index; otherwise usek. Write the last remaining cell ontok, then decrement the count. - The same cell is not drawn twice.
resetclears the map and restores the count tom * n. - The row is
x / nand the column isx % n. A1by1matrix has one flip, and it is that cell.