You are given the number of rows m
and the number of columns n
of a 2D binary matrix where all values are initially 0. Implement the FlipMatrix
class:
FlipMatrix(m: int, n: int)
: Initializes the object with the size of the binary matrix m
x n
.flip() -> List[int]
: Returns a random position [row, col]
of a 0 in the matrix. The 0 at this position will now be set to 1. This function should ensure that each position is flipped at most once.reset() -> None
: Resets all values of the matrix back to 0.You need to implement these functions such that each flip is done in O(1)
time on average, and the memory used is O(m * n)
.
m
and n
are positive integers within reasonable limits.m * n
. This helps us to simplify the problem to a 1D array.By storing only the necessary information to remap positions, we efficiently manage and maintain matrix flips.
import random
class FlipMatrix:
def __init__(self, m: int, n: int):
self.m = m
self.n = n
self.total = m * n
self.flips_map = {}
self.available = self.total
def flip(self) -> List[int]:
rand_index = random.randint(0, self.available - 1)
self.available -= 1
# Get the mapped position or default to rand_index
flip_pos = self.flips_map.get(rand_index, rand_index)
# Update the map to reflect this position has been flipped
self.flips_map[rand_index] = self.flips_map.get(self.available, self.available)
return [flip_pos // self.n, flip_pos % self.n]
def reset(self) -> None:
self.flips_map = {}
self.available = self.total
# Example usage:
# obj = FlipMatrix(m, n)
# param_1 = obj.flip()
# obj.reset()
O(1)
, setting up initial variables.O(1)
on average, due to constant-time updates and dictionary access.O(1)
, resetting the dictionary and counter.This ensures that the operations are efficient and scalable with respect to the matrix size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?