Random Flip Matrix

Problem Id: 519 Difficulty: Medium


Intuition

Solution


class Solution:

    def __init__(self, n_rows: int, n_cols: int):
        self.visited = []
        self.rows = n_rows
        self.cols = n_cols

    def flip(self) -> List[int]:
        total = self.rows * self.cols - len(self.visited)
        n = random.randint(0, total - 1)
        for i in self.visited:
            if i <= n:
                n += 1
        self.visited.append(n)
        self.visited.sort()
        return n % self.rows, n // self.rows

    def reset(self) -> None:
        self.visited = []


# Your Solution object will be instantiated and called as such:
# obj = Solution(n_rows, n_cols)
# param_1 = obj.flip()
# obj.reset()