Skip to content

Instantly share code, notes, and snippets.

@vishoo7
Last active August 5, 2017 17:52
Show Gist options
  • Save vishoo7/a715f65b1a88acfc81fe330fac16ff02 to your computer and use it in GitHub Desktop.
Save vishoo7/a715f65b1a88acfc81fe330fac16ff02 to your computer and use it in GitHub Desktop.
Interview question: implement a class that will take a list of lists and return the next item in a randomly selected list
from random import Random
class RandomItemRetriever:
'''
This class will take a list of lists and return the next item in a randomly selected list.
Time: O(1)
Space: O(n) where n = number of lists
'''
def __init__(self, lists):
# store original data (never mutated)
self.lists = lists
# next index for each list
self.indexes = [0] * len(lists)
# array_idxs
self.array_idxs = [x for x in range(len(lists))]
# pointer to first available array
self.start = 0
def get_next(self):
if self.start >= len(self.array_idxs):
raise StopIteration()
r = Random()
idx = r.randint(self.start, len(self.array_idxs)-1)
arr_idx = self.array_idxs[idx]
item = self.lists[arr_idx][self.indexes[arr_idx]]
self.indexes[arr_idx] += 1
# if we're done with a list then put it at start of self.arrays and increment self.start
if self.indexes[arr_idx] == len(self.lists[arr_idx]):
self.array_idxs[self.start], self.array_idxs[arr_idx] = self.array_idxs[arr_idx], self.array_idxs[self.start]
self.start += 1
return item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment