tinycodinglm / cp /cp-10026.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.7 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Random Flip Matrix (Difficulty: Medium)
Tags: Hash Table, Math, Reservoir Sampling, Randomized

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:

Example 1:
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.
Assistant

Time: ctor: O(1)

flip: O(1)

reset: O(min(f, r * c))

Space: O(min(f, r * c))

import random

class Solution(object):

markdown
def __init__(self, n_rows, n_cols):
    """
    :type n_rows: int
    :type n_cols: int
    """
    self.__n_rows = n_rows
    self.__n_cols = n_cols
    self.__n = n_rows*n_cols
    self.__lookup = {}
    

def flip(self):
    """
    :rtype: List[int]
    """
    self.__n -= 1
    target = random.randint(0, self.__n)
    x = self.__lookup.get(target, target)
    self.__lookup[target] = self.__lookup.get(self.__n, self.__n)
    return divmod(x, self.__n_cols)
    

def reset(self):
    """
    :rtype: void
    """
    self.__n = self.__n_rows*self.__n_cols
    self.__lookup = {}