#519

Random Flip Matrix

Medium
Hash TableMathReservoir SamplingRandomizedHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(n²)
O(n)
💡

Intuition

Time O(1)Space O(n)

This approach uses a mapping technique to efficiently track the available indices without needing to maintain a separate list. We can use a HashMap to map the flipped indices to the last available index, allowing us to select random indices without iterating through the entire matrix.

⚙️

Algorithm

4 steps
  1. 1Step 1: Maintain a count of total available cells and a mapping of flipped indices to available indices.
  2. 2Step 2: When flipping, randomly select an index and swap it with the last available index in the mapping.
  3. 3Step 3: Update the mapping and decrement the available count.
  4. 4Step 4: On reset, clear the mapping and reset the count.
solution.py20 lines
1import random
2
3class Solution:
4    def __init__(self, m: int, n: int):
5        self.m = m
6        self.n = n
7        self.total = m * n
8        self.flipped = {}
9
10    def flip(self):
11        idx = random.randint(0, self.total - 1)
12        if idx in self.flipped:
13            idx = self.flipped[idx]
14        self.flipped[idx] = self.flipped.get(self.total - 1, self.total - 1)
15        self.total -= 1
16        return [idx // self.n, idx % self.n]
17
18    def reset(self):
19        self.flipped.clear()
20        self.total = self.m * self.n

Complexity note: The time complexity is O(1) for the flip operation because we are only performing a constant amount of work regardless of the size of the matrix. The space complexity is O(n) for storing the flipped indices in the HashMap.

  • 1Using a HashMap allows for efficient tracking of flipped indices.
  • 2Random selection without needing to iterate through the entire matrix reduces time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.