classSolution:def__init__(self, w: List[int]):
self.w = w
self.total =sum(w)defpickIndex(self)->int:
target = self.total * random.random()
curSum =0for i inrange(len(self.w)):
curSum += self.w[i]if curSum > target:return i
Time & Space Complexity
Time complexity: O(n) for initializing and O(n) for each pickIndex() function call.