Random Flip Matrix - Problem

You are given an m x n binary grid matrix with all values initially set to 0. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flip it to 1.

All indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls to the built-in random function and optimize time and space complexity.

Implement the Solution class:

  • Solution(int m, int n) - Initializes the object with the size of the binary matrix m and n
  • int[] flip() - Returns a random index [i, j] where matrix[i][j] == 0 and flips it to 1
  • void reset() - Resets all values of the matrix to 0

Input & Output

Example 1 — Basic 2x3 Matrix
$ Input: m = 2, n = 3
Output: [0,1] (or any valid position)
💡 Note: Initialize 2×3 matrix with all 0s. First flip() call can return any position like [0,1], which gets flipped to 1. Matrix becomes [[0,1,0],[0,0,0]].
Example 2 — Small 1x2 Matrix
$ Input: m = 1, n = 2
Output: [0,0] or [0,1]
💡 Note: With only 2 positions available, first flip returns either [0,0] or [0,1] with equal probability. Second flip would return the remaining position.
Example 3 — Single Cell Matrix
$ Input: m = 1, n = 1
Output: [0,0]
💡 Note: Only one position [0,0] available. First flip() must return [0,0]. Any subsequent flip() calls would have no valid positions (in practice, problem guarantees valid calls).

Constraints

  • 1 ≤ m, n ≤ 104
  • At most 1000 calls will be made to flip and reset
  • It is guaranteed that there will be at least one free cell for each call to flip

Visualization

Tap to expand
Random Flip Matrix: From All 0s to Random 1sInitial 2×3 Matrix000000After flip() → [0,1]010000Random selection flips position [0,1] from 0 to 1🎲
Understanding the Visualization
1
Initial State
m×n matrix filled with all 0s
2
Random Selection
Pick random position where matrix[i][j] == 0
3
Flip Result
Change selected position to 1 and return coordinates
Key Takeaway
🎯 Key Insight: Use Fisher-Yates shuffle to efficiently select from shrinking pool of available positions
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
32.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen