Random Flip Matrix Problem
Description
LeetCode Problem 519.
There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity.
Implement the Solution class:
- Solution(int m, int n) Initializes the object with the size of the binary matrix m and n.
- int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1.
- void reset() Resets all the values of the matrix to be 0.
Example 1:
Input
["Solution", "flip", "flip", "flip", "reset", "flip"]
[[3, 1], [], [], [], [], []]
Output
[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]
Explanation
Solution solution = new Solution(3, 1);
solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]
solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
Constraints:
- 1 <= m, n <= 10^4
- There will be at least one free cell for each call to flip.
- At most 1000 calls will be made to flip and reset.
Solution
Approach: Virtual Fisher–Yates Shuffle with a Hash Map
The grid can have 108 cells, so we cannot store it, and picking random cells until we hit a 0 gets slow and uses many random calls once the grid fills up. Instead, number the cells 0 … m·n − 1 (cell k is row k / n, column k % n) and run a Fisher–Yates shuffle on that list without building it.
Picture an array slots whose first remaining entries are exactly the cells that are still 0. At the start remaining = m·n and slots[k] = k. To flip:
- Pick a random
slotin[0, remaining). One random call per flip. - The answer is the cell stored there,
slots[slot]. - Move the cell from the last free slot,
slots[remaining − 1], intoslot, and decreaseremaining. The flipped cell drops out of the free range, and the free cells stay packed at the front.
Almost every slot still holds its own number, so a hash map moved stores only the slots whose content has changed; a slot that is not in the map holds itself. Each flip adds at most one entry.
reset sets remaining = m·n and clears the map.
The detail to get right is step 3: read the cell for slot before overwriting it, and look up the last slot through the map as well (it may already hold a moved cell), not just use the number remaining − 1.
Each free cell is equally likely to be picked, because the random number is uniform over exactly the free slots.
Complexity: O(1) expected time per flip and O(k) space for the map, where k is the number of flips since the last reset.
import random
class Solution:
def __init__(self, m: int, n: int):
self.m = m
self.n = n
self.reset()
def flip(self) -> List[int]:
# Cells are numbered 0 .. m*n-1. The first `remaining` slots hold the cells that
# are still 0; a slot not in `moved` holds its own number.
slot = random.randrange(self.remaining)
cell = self.moved.get(slot, slot)
# Fill the chosen slot with the cell from the last free slot, then shrink the range.
self.remaining -= 1
self.moved[slot] = self.moved.get(self.remaining, self.remaining)
return [cell // self.n, cell % self.n]
def reset(self) -> None:
self.remaining = self.m * self.n
self.moved = {} # slot -> cell, only for slots whose cell was swapped in
# Your Solution object will be instantiated and called as such:
# obj = Solution(m, n)
# param_1 = obj.flip()
# obj.reset()