LeetCode 519, Medium. Topics: Hash Table, Math, Reservoir Sampling, Randomized. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:
Problem
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.
Examples
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
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026