Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

519. Random Flip Matrix

Explanation

To solve this problem efficiently, we can use a combination of techniques. We can map the 2D grid to a 1D array to optimize memory usage. Then, we can use a map or a set to keep track of the available indices that can be flipped. When flipping an index, we need to ensure that it is removed from the available indices set and update the mapping accordingly. Resetting the matrix simply involves clearing the set of available indices.

The time complexity for each flip operation is O(1), as we are choosing an available index randomly. The space complexity is O(m*n) for storing the matrix and O(k) for storing the set of available indices, where k is the number of available indices.

import java.util.*;

class Solution {
    private int rows, cols, total;
    private Random rand;
    private Map<Integer, Integer> map;

    public Solution(int m, int n) {
        rows = m;
        cols = n;
        total = m * n;
        rand = new Random();
        map = new HashMap<>();
    }

    public int[] flip() {
        int r = rand.nextInt(total--);
        int x = map.getOrDefault(r, r);
        map.put(r, map.getOrDefault(total, total));
        return new int[]{x / cols, x % cols};
    }

    public void reset() {
        map.clear();
        total = rows * cols;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.