> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Random Flip Matrix Python Solution with Tests

> Tested Python solution for LeetCode 519 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 519, [Medium](/catalog/medium). Topics: [Hash Table](/catalog/topics/hash-table), [Math](/catalog/topics/math), Reservoir Sampling, Randomized. [View on LeetCode](https://leetcode.com/problems/random-flip-matrix/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 519   # by problem number
lcpy gen -s random_flip_matrix   # by problem name
```

## Problem

There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.

Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the 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]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.

### Examples

```
Input
["Solution", "flip", "flip", "flip", "reset", "flip"]
[[3, 1], [], [], [], [], []]
Output
[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]

Explanation
Solution solution = new Solution(3, 1);
solution.flip();  // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
solution.flip();  // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]
solution.flip();  // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip();  // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
```

### Constraints

* `1 <= m, n <= 10^4`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/random_flip_matrix/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/random_flip_matrix/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import random


class Solution:
    # Time: __init__ O(1), flip O(1), reset O(1)
    # Space: O(k) where k is the number of flips since the last reset
    def __init__(self, m: int, n: int) -> None:
        self.m = m
        self.n = n
        self.total = m * n
        self.available = self.total
        self.swapped: dict[int, int] = {}

    def flip(self) -> list[int]:
        idx = random.randrange(self.available)
        self.available -= 1
        picked = self.swapped.get(idx, idx)
        self.swapped[idx] = self.swapped.get(self.available, self.available)
        return [picked // self.n, picked % self.n]

    def reset(self) -> None:
        self.available = self.total
        self.swapped = {}
```

## Complexity

| Time | Space |
| - | - |
| **init** O(1), flip O(1), reset O(1) | O(k) where k is the number of flips since the last reset |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.