↓Skip to main content
  1. LeetCode/

LeetCode 703: Kth Largest Element in a Stream

·1 min· ·
LeetCode Easy Tree Design Binary-Search-Tree Heap-Priority-Queue
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-31

  • Submissions: Accepted (first try)

Approach
#

Only the k largest numbers matter. Keep a min-heap (Heap Template 1), popping the smallest whenever it exceeds k; the top is the smallest of those k, i.e. the k-th largest.

My Solution
#

class KthLargest:
    def __init__(self, k: int, nums: List[int]):
        self.k, self.heap = k, []
        for x in nums:
            self.add(x)

    def add(self, val: int) -> int:
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        return self.heap[0]

Complexity
#

Each add is O(log k), space O(k).

Mistakes to Avoid
#

  • The initial nums may have fewer than k items, so the heap may not be full at construction.

Interview Explanation
#

I keep a min-heap of at most k items, popping the smallest after an insert pushes it past k; the top is the k-th largest. O(log k) each.

Related

LeetCode 700: Search in a Binary Search Tree
·1 min
LeetCode Easy Tree Binary-Search-Tree Binary-Tree
LeetCode 700 note: go left when the node is larger, right when smaller, and return the node when found
LeetCode 530: Minimum Absolute Difference in BST
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Search-Tree
LeetCode 530 note: a BST’s in-order is ascending, so the minimum difference is between in-order neighbors; remember the previous value and compare
LeetCode 501: Find Mode in Binary Search Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 501 note: a BST’s in-order is sorted, so equal values are contiguous; count the current run during in-order, resetting the answer on a new maximum and appending on a tie
LeetCode 108: Convert Sorted Array to Binary Search Tree
·1 min
LeetCode Easy Array Divide-and-Conquer Tree Binary-Search-Tree
LeetCode 108 note: the middle element becomes the root and each half recurses; the halves differ by at most one, so the tree is balanced
LeetCode 506: Relative Ranks
·1 min
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 note: sort indices by score descending, give medals to the top three and rank strings to the rest, writing back into the original positions
LeetCode 705: Design HashSet
·2 mins
LeetCode Easy Array Hash-Table Linked-List Design
LeetCode 705 note: a fixed number of buckets, with the key modulo the bucket count choosing the bucket and a list per bucket handling collisions