Leetcode 519: Random Flip Matrix

grid47
grid47
Exploring patterns and algorithms
Sep 16, 2024 6 min read

A matrix where cells are randomly flipped, with each flipped cell softly glowing as it changes state.
Solution to LeetCode 519: Random Flip Matrix Problem

You are given a binary grid of size m x n, where each cell is initially set to 0. The task is to design an algorithm that can randomly pick a cell that is still 0, flip it to 1, and ensure that all available cells are equally likely to be selected.
Problem
Approach
Steps
Complexity
Input: The input consists of a pair of integers m and n representing the size of the grid, followed by a sequence of operations.
Example: [3, 1], [], [], [], []
Constraints:
• 1 <= m, n <= 10^4
• There will always be at least one cell with value 0 for every flip operation.
• No more than 1000 flip and reset operations will be performed.
Output: The output should be an array representing the randomly selected index [i, j] for the flip operation, and null for other operations.
Example: [null, [1, 0], [2, 0], [0, 0], null, [2, 0]]
Constraints:
• The flip operation should return the index of a randomly selected cell that is still 0 and flips it to 1.
Goal: To randomly select an index where the value is 0, flip it to 1, and ensure equal likelihood for all available indices.
Steps:
• 1. Maintain a list or map to track available cells with value 0.
• 2. For each flip, randomly pick an index from the list of available cells.
• 3. After picking, flip the cell to 1 and update the list accordingly.
• 4. Reset the grid when the reset operation is called, restoring all values to 0.
Goal: The constraints for the input and output of the problem.
Steps:
• 1 <= m, n <= 10^4
• At least one free cell will be available for each flip call.
• No more than 1000 flip and reset operations.
Assumptions:
• The grid is initially filled with 0s.
• Each flip picks a valid available index and updates the grid.
Input: [3, 1], [], [], [], []
Explanation: A grid of size 3x1 is initialized with all zeros. Each flip returns a random index of a free cell, and after resetting, the grid is restored to its initial state.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus