Leetcode 519. Random Flip Matrix Sure, I’ll help you solve the problem “519. Random Flip Matrix” from LeetCode. Below is the structured approach:
You are given the number of rows m
and number of columns n
of a 2D binary matrix which is initially all 0s. You need to implement the Solution
class:
Solution(int m, int n)
Initializes the object with the number of rows m
and columns n
.vector<int> flip()
Returns a random index [r, c]
(row and column index) such that the cell is 0, and then changes it to 1.void reset()
Resets all the cells of the matrix to be 0.Your efficient solution should ensure that flip
works in almost constant time with no significant extra memory overhead.
Q: Is it guaranteed that the matrix will not exceed a certain size?
A: Yes, but the goal is to handle large matrices efficiently.
Q: Can the same cell be flipped more than once without resetting?
A: No, once flipped, it becomes 1 and should not be flipped again until a reset.
Q: How should we handle cases where all cells are flipped?
A: If all cells are flipped, calling flip
should be avoided or can throw an exception.
Here is the C++ implementation of the above strategy:
#include <vector>
#include <unordered_map>
#include <cstdlib>
using namespace std;
class Solution {
private:
int rows, cols, total;
unordered_map<int, int> flipped;
public:
Solution(int m, int n) : rows(m), cols(n), total(m * n) {
srand(time(0)); // Seeding for randomness
}
vector<int> flip() {
int randPos = rand() % total--;
int actualPos = randPos;
if (flipped.find(randPos) != flipped.end()) {
actualPos = flipped[randPos];
}
if (flipped.find(total) != flipped.end()) {
flipped[randPos] = flipped[total];
} else {
flipped[randPos] = total;
}
return {actualPos / cols, actualPos % cols};
}
void reset() {
total = rows * cols;
flipped.clear();
}
};
Solution
): Initialize the matrix dimensions and total cells. Seed the random number generator.flip
): Pick a random position. Use a hash map to find the actual position to be flipped. Swap mappings for efficient future access.reset
): Clear the map and reset the total cells count.flip
: O(1) amortized - HashMap operations (insert/find) are O(1) on average.reset
: O(1) - Just clearing the hash map and resetting a counter.This solution ensures that the flip operation runs efficiently even for a large 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?