Catalogue
Data Stream
703. Kth Largest Element in a Stream
- heap
1 | class KthLargest(object): |
346. Moving Average from Data Stream
- sliding window : deque - double queue
1 | class MovingAverage(object): |
295. Find Median from Data Stream
- min Heap, max Heap
1 | class MedianFinder(object): |
- follow up : what if the number of element is toooo large to be stored into the memory?
Find the first non-repeating character from a Stream
Use Case:
- We need to somehow record which one is the First (order)
When a new element comes in
- we found that previous solution is now not the solution any more, we need to update the solution to the next one.(Use a doubl linked list)
- We also need to record what kind of letters that have appeared (non-repeating)
- Hash Map <key:character, val:Node>
(Same with LRU!!!)
Sliding Window
Slinding Window Average
- Time : O(1), Space :(window size)
- Queue to maintain the window
- variable sum to record sum , update O(1)
239. Sliding Window Maximum
total data - n, window size - k
Solution1. Naive
Time : O((n-k)k), (O(k) for online data stream)
Solution2. Heap
Time : O((n-k)logk)
- Initialization:insert all first k elements into the max-heap.
- Then: when the sliding window moves to the right side step by step
1 new element comes in.
1 left-most element should be removed from the sliding window. bu we can temoporarily keep it in the heap, until it becomes the top element in the heap. lazy deletion
(value, index)
1 | class Solution(object): |
- When we want to call max_heap.top(), the only thing we should be careful about is to check, whether this top elemtns’s index is < left border of the sliding window. If so, keep poping it out.
Solution3. Deque
Time : O(n)
- We must maintain all the values in the dequeue to keep them in a descending order.
- because when a new element X comes in, if it is bigger and newer than the right most element r, then r cannot be the solution. whatsoever, we can just delete r
1 | class Solution(object): |
- So the dequeue[left-most] is the final result to return whenever the window slides one step to the right.
480. Sliding Window Median
- double heap + lazy clear
1 | class Solution(object): |