def __getTopK(self, frequencyMap): # initialize Heap minHeap = [] # for each sentence, maintain top K sentences seen so far for sent in frequencyMap: frequency = frequencyMap[sent] currentObject = FrequencyMap(sent, frequency) if (len(minHeap) == self.k): minObject = remove(minHeap) if (currentObject > minObject): insert(minHeap, currentObject) else: insert(minHeap, minObject) else: insert(minHeap, currentObject) # put the remaining top K sentences in a stack for extracting them in descending order stack = [] while (len(minHeap) > 0): currentObject = remove(minHeap) stack.append(currentObject.sentence) # add to the final list of sentences in descending order finalList = [] while (len(stack) > 0): finalList.append(stack.pop()) # return the top K sentences return finalList
def lastStoneWeight(self, stones: List[int]) -> int: # Time: O(NlogN + N/2logN) ~ O(NlogN) # Space: O(N) for maxHeap # initializations maxHeap = [] # filling maxHeap with -1 times the actual value for i in range(len(stones)): insert(maxHeap, -stones[i]) # remove last 2 elements (as numbers are negative an we have only minHeap in py) while (len(maxHeap) > 1): first = remove(maxHeap) second = remove(maxHeap) # if equal => don't do anything and continue the loop if (first == second): continue # otherwise insert -1 times the absolute value of top 2 numbers insert(maxHeap, -1 * abs(first - second)) # if one element present => take out the absolute value # else return 0 if (len(maxHeap) == 1): return (-1 * remove(maxHeap)) else: return 0
def __init__(self, k: int, nums: List[int]): # initialize in such a way that your Data Structure has only k largest elements self.minHeap = [] self.capacity = k for num in nums: insert(self.minHeap, num) if (len(self.minHeap) > k): remove(self.minHeap)
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]: heap = [] result = [] for p in points: dist = -(p[0]**2 + p[1]**2) insert(heap, [dist, p]) if len(heap) > K: remove(heap) for i in heap: result.append(i[1]) return result
def leastInterval(self, tasks: List[str], n: int) -> int: # initializations frequencyMap = {} T = len(tasks) maxHeap = [] time = 0 # fill frequency map for task in tasks: if task in frequencyMap: frequencyMap[task] += 1 else: frequencyMap[task] = 1 # insert all frequency map info into the Heap for char in frequencyMap: charFreq = FrequencyMap(char, frequencyMap[char]) insert(maxHeap, charFreq) # iterate until nothing is left in Heap while (len(maxHeap) > 0): # to calculate cooldown time tempTime = 0 bufferList = [] # iterate cooldown time ends while (tempTime <= n): # If any element in Heap if (len(maxHeap) > 0): maxCharFreq = maxHeap[0] if (maxCharFreq.freq > 1): # if frequency > 1 maxCharFreq.freq -= 1 bufferList.append(maxCharFreq) # add to buffer list remove(maxHeap) # remove max element anyway time += 1 # increment overall time # if nothing exists in both Heap and buffer list => we're done if (len(maxHeap) == 0 and len(bufferList) == 0): break # increment twmp time until <= cooldown time tempTime += 1 # now after cooldown, add each entry from Buffer list to Max Heap for eachEntry in bufferList: insert(maxHeap, eachEntry) # return overall time return time
def getValues(self, countMap): heap = [] for key in countMap: count = countMap[key] p = Pair(key, count) insert(heap, p) if len(heap) > 3: remove(heap) stack = [] while len(heap) > 0: stack.append(remove(heap).sentence) return stack[::-1]
def minMeetingRooms(self, intervals): if not intervals: return 0 heap = [] intervals = sorted(intervals, key=lambda interval: interval.start) for i in intervals: if len(heap) == 0: insert(heap, i.end) continue if i.start >= heap[0]: remove(heap) insert(heap, i.end) return len(heap)
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]: minHeap = [] # once the size overloads => remove the max element from the heap for point in points: newPoint = Point(point) insert(minHeap, newPoint) if (len(minHeap) > K): remove(minHeap) return [each.point for each in minHeap]
def add(self, val: int) -> int: # first insert the new value and if size exceeds => remove the min value insert(self.minHeap, val) if (len(self.minHeap) > self.capacity): remove(self.minHeap) # kth largest would be == first element return self.minHeap[0] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)
def park(self): #heap has parking spots if len(self.heap) > 0: return remove(self.heap) else: print("Parking lot full.") return None
def nthUglyNumber(self, n: int) -> int: # edge case check if (n == 1): return n # initializations minHeap = [1] visited = set([1]) count = 0 primes = [2, 3, 5] poppedElement = 1 # iterate until nth ugly number while (count < n): # remove min element from min heap poppedElement = remove(minHeap) count += 1 # for each of the primes, mutlipy min element and push into heap if not in the hash set for prime in primes: nextElement = poppedElement * prime if (nextElement not in visited): visited.add(nextElement) insert(minHeap, nextElement) # return the nth popped element from min heap return poppedElement
def getNewsFeed(self, userId: int) -> List[int]: """ Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. """ q = [] followers = self.UserMap[userId] followers.add(userId) for f in followers: for tweet in self.TweetsMap[f]: t, post = tweet[0], tweet[1] if len(q) < 10: insert(q, (t, post)) elif t > q[0][0]: remove(q) insert(q, (t, post)) result = [] while q: t, post = remove(q) result.append(post) return result[::-1]
def park(self) -> 'ParkingSpace': # if slots available => return the closest slot available if (len(self.__priorityQueue) > 0): parkingSpace = remove(self.__priorityQueue) return parkingSpace # else do nothing else: print('Oops!!! The Parking Lot is Full') return None
def addNum(self, num: int) -> None: # if upper half min heap is empty or current element is greater than its min (=> current element's place # is definitely in upper half whereas not sure about the heap's min element). if ( len(self.upperHalfMinHeap) == 0 or num > self.upperHalfMinHeap[0] ): insert(self.upperHalfMinHeap, num) else: insert(self.lowerHalfMaxHeap, -num) # re-balance according to the sizes while ( abs(len(self.upperHalfMinHeap) - len(self.lowerHalfMaxHeap)) >= 2): if (len(self.upperHalfMinHeap) > len(self.lowerHalfMaxHeap)): number = remove(self.upperHalfMinHeap) insert(self.lowerHalfMaxHeap, -number) else: number = remove(self.lowerHalfMaxHeap) insert(self.upperHalfMinHeap, -number)
def nthUglyNumber(self, n: int) -> int: hashset = set() heap = [] heapq.heappush(heap, 1) hashset.add(1) for i in range(n-1): curr = remove(heap) n2 = 2 * curr n3 = 3 * curr n5 = 5 * curr if n2 not in hashset: hashset.add(n2) insert(heap, n2) if n3 not in hashset: hashset.add(n3) insert(heap, n3) if n5 not in hashset: hashset.add(n5) insert(heap, n5) return remove(heap)
def getNewsFeed(self, userId: int) -> List[int]: """ Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. """ self._newUser(userId) tweet_list = [] followedUsers = self.user_follower[userId] if followedUsers: for followee in followedUsers: if followee in self.user_tweet and len( self.user_tweet[followee]) > 0: for tweet in self.user_tweet[followee]: insert(tweet_list, tweet) if len(tweet_list) > self.feed_limit: remove(tweet_list) output = [] while len(tweet_list) > 0: output.append(remove(tweet_list).tweetId) return output[::-1]
def topKFrequent(self, nums: List[int], k: int) -> List[int]: # edge case checks if (nums == None or len(nums) == 0): return [] # initializations finalResult = [0 for i in range(k)] frequencyMap = {} minHeap = [] # calculate number-count HashMap and then convert to custom class pairs while pushing into Heap for num in nums: if num not in frequencyMap: frequencyMap[num] = 1 else: frequencyMap[num] += 1 # for each number in the Map for number in frequencyMap: # create the pair class object currentPair = NumberFrequencyPair(number, frequencyMap[number]) # insert the element insert(minHeap, currentPair) # if size exceeds k => remove the minimum frequent element if len(minHeap) > k: remove(minHeap) # now, put all top k frequent elements in correct locations (in reverse directions as it is a min heap) for i in range(k - 1, -1, -1): poppedPair = remove(minHeap) finalResult[i] = poppedPair.getNumber() # return the final result return finalResult
def findMinNoOfMeetingRooms(self, intervals: list) -> int: # edge case check if (intervals == None or len(intervals) == 0): return 0 # sort the array based on start times intervals.sort(key=lambda x: x.start) # initialize minHeap with one element minHeap = [intervals[0]] # first check the min end time of elements using minHeap # if next element in sorted array has end time less than min end time => overlapping => add to minHeap # else remove min end time element as no other interval clashes for i in range(1, len(intervals)): minEnd = minHeap[0].end if (intervals[i].start >= minEnd): remove(minHeap) insert(minHeap, intervals[i]) # return the count left in minHeap as those many rooms will be required. return len(minHeap)
def topKFrequent(self, nums: List[int], k: int) -> List[int]: if not nums: return nums countMap = {} for n in nums: if n in countMap: countMap[n] += 1 else: countMap[n] = 1 heap = [] for key, value in countMap.items(): heap.append((-value, key)) heapify(heap) result = [] l = len(heap) for i in range(k): result.append(remove(heap)[1]) return result