algoadvance

Leetcode 519. Random Flip Matrix Sure, I’ll help you solve the problem “519. Random Flip Matrix” from LeetCode. Below is the structured approach:

Problem Statement

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:

Your efficient solution should ensure that flip works in almost constant time with no significant extra memory overhead.

Clarifying Questions

  1. Q: Is it guaranteed that the matrix will not exceed a certain size?
    A: Yes, but the goal is to handle large matrices efficiently.

  2. 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.

  3. 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.

Strategy

Code

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();
    }
};

Explanation

Time Complexity

This solution ensures that the flip operation runs efficiently even for a large matrix size.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI