Skip to content

Commit 74e1f4c

Browse files
authored
Create random-flip-matrix.py
1 parent c0dd972 commit 74e1f4c

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Python/random-flip-matrix.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Time: O(1)
2+
# Space: O(min(f, r * c))
3+
4+
# You are given the number of rows n_rows and
5+
# number of columns n_cols of a 2D binary matrix
6+
# where all values are initially 0.
7+
# Write a function flip which chooses a 0 value uniformly at random,
8+
# changes it to 1, and then returns the position [row.id, col.id] of
9+
# that value. Also, write a function reset which sets all values back to 0.
10+
# Try to minimize the number of calls to system's Math.random()
11+
# and optimize the time and space complexity.
12+
#
13+
# Note:
14+
# - 1 <= n_rows, n_cols <= 10000
15+
# - 0 <= row.id < n_rows and 0 <= col.id < n_cols
16+
# - flip will not be called when the matrix has no 0 values left.
17+
# - the total number of calls to flip and reset will not exceed 1000.
18+
# Example 1:
19+
#
20+
# Input:
21+
# ["Solution","flip","flip","flip","flip"]
22+
# [[2,3],[],[],[],[]]
23+
# Output: [null,[0,1],[1,2],[1,0],[1,1]]
24+
# Example 2:
25+
#
26+
# Input:
27+
# ["Solution","flip","flip","reset","flip"]
28+
# [[1,2],[],[],[],[]]
29+
# Output: [null,[0,0],[0,1],null,[0,0]]
30+
# Explanation of Input Syntax:
31+
#
32+
# The input is two lists:
33+
# the subroutines called and their arguments.
34+
# Solution's constructor has two arguments, n_rows and n_cols.
35+
# flip and reset have no arguments.
36+
# Arguments are always wrapped with a list, even if there aren't any.
37+
38+
import random
39+
40+
41+
class Solution(object):
42+
43+
def __init__(self, n_rows, n_cols):
44+
"""
45+
:type n_rows: int
46+
:type n_cols: int
47+
"""
48+
self.__n_rows = n_rows
49+
self.__n_cols = n_cols
50+
self.__n = n_rows*n_cols
51+
self.__lookup = {}
52+
53+
54+
def flip(self):
55+
"""
56+
:rtype: List[int]
57+
"""
58+
self.__n -= 1
59+
target = random.randint(0, self.__n)
60+
x = self.__lookup.get(target, target)
61+
self.__lookup[target] = self.__lookup.get(self.__n, self.__n)
62+
return divmod(x, self.__n_cols)
63+
64+
65+
def reset(self):
66+
"""
67+
:rtype: void
68+
"""
69+
self.__n = self.__n_rows*self.__n_cols
70+
self.__lookup = {}
71+
72+
73+
# Your Solution object will be instantiated and called as such:
74+
# obj = Solution(n_rows, n_cols)
75+
# param_1 = obj.flip()
76+
# obj.reset()

0 commit comments

Comments
 (0)