Leetcode 519. Random Flip Matrix
You are given the number of rows m
and the number of columns n
of a 2D binary matrix initialized with all 0
s. Implement the FlipMatrix
class:
FlipMatrix(int m, int n)
Initializes the object with the size of the binary matrix m
x n
.int[] flip()
Randomly flips a 0
to 1
and returns the position [row_id, col_id]
of that flip.void reset()
Resets all the values of the matrix to 0
.You should decide to use neither a 2D array nor dynamic memory allocation tracked in real-time, not exceeding O(1) space complexity for the matrix representation.
flip()
function return the same position [row_id, col_id]
if all elements have already been flipped to 1
?Based on typical problem constraints and observed behavior:
1
, a common approach is to throw an error or reset automatically, but this problem usually relies on continuing to flip even if the matrix was fully occupied.Let’s proceed to the coding section.
flip()
, randomly pick an index from available zero-positions and mark it flipped.reset()
, reset all data structures to start over.import java.util.*;
class FlipMatrix {
private int m, n, total;
private Map<Integer, Integer> map;
private Random rand;
public FlipMatrix(int m, int n) {
this.m = m;
this.n = n;
this.total = m * n;
this.map = new HashMap<>();
this.rand = new Random();
}
public int[] flip() {
int r = rand.nextInt(total--);
int x = map.getOrDefault(r, r);
map.put(r, map.getOrDefault(total, total));
int row = x / n;
int col = x % n;
return new int[]{row, col};
}
public void reset() {
this.total = m * n;
this.map.clear();
}
}
FlipMatrix
): O(1)flip
): O(1) - Constant time to generate and store mappings.reset
): O(1) - Linear time in terms of clearing the map and resetting the counter.This approach effectively minimizes space usage while maintaining constant-time complexity for the primary operations.
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?