Random Flip Matrix — LeetCode 519 Python Solution
MediumReservoir SamplingHash TableMathRandomized
- Problem
- #519
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["Solution", "flip", "flip", "flip", "reset", "flip"]
- Output
- [null, [1, 0], [2, 0], [0, 0], null, [2, 0]]
- Explanation
- Solution solution = new Solution(3, 1);
Python solution
Python
class Solution:
def __init__(self, m: int, n: int):
self.m = m
self.n = n
self.total = m * n
self.mp = {}
def flip(self) -> List[int]:
self.total -= 1
x = random.randint(0, self.total)
idx = self.mp.get(x, x)
self.mp[x] = self.mp.get(self.total, self.total)
return [idx // self.n, idx % self.n]
def reset(self) -> None:
self.total = self.m * self.n
self.mp.clear()
# Your Solution object will be instantiated and called as such:
# obj = Solution(m, n)
# param_1 = obj.flip()
# obj.reset()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 519. Random Flip Matrix is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 519. Random Flip Matrix?
- LeetCode 519. Random Flip Matrix is rated Medium on LeetCode.
- What is the time complexity of LeetCode 519. Random Flip Matrix?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 519. Random Flip Matrix?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 519. Random Flip Matrix cover?
- LeetCode 519. Random Flip Matrix is tagged Reservoir Sampling, Hash Table, Math and Randomized on LeetCode.