← Home

703. Kth Largest Element in a Stream

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
data structure designC++Markdown
703

This is one of those problems where the clean idea matters more than the amount of code. For 703. Kth Largest Element in a Stream, the solution in this repository is mainly a data structure design solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: data structure design, heap / priority queue, greedy.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are add.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The heap keeps the best candidate available without sorting the whole world every time.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
03
04Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
05
06Example:
07
08int k = 3;
09int[] arr = [4,5,8,2];
10KthLargest kthLargest = new KthLargest(3, arr);
11kthLargest.add(3);   // returns 4
12kthLargest.add(5);   // returns 5
13kthLargest.add(10);  // returns 5
14kthLargest.add(9);   // returns 8
15kthLargest.add(4);   // returns 8
16Note: 
17You may assume that nums' length ≥ k-1 and k ≥ 1.
18**/
19
20//Runtime: 192 ms, faster than 11.41% of C++ online submissions for Kth Largest Element in a Stream.
21//Memory Usage: 19.5 MB, less than 47.71% of C++ online submissions for Kth Largest Element in a Stream.
22
23class KthLargest {
24private:
25    vector<int> kLargest;
26public:
27    /**
28    solution.cpp: In static member function 'static KthLargest*      __DriverSolution__::__helperConstructor__(const string&, const std::vector<std::__cxx11::basic_string<char> >&)':
29    Line 99: Char 41: error: cannot bind non-const lvalue reference of type 'std::vector<int>&' to an rvalue of type 'std::vector<int>'
30    **/
31    // KthLargest(int k, vector<int>& nums) {
32    KthLargest(int k, vector<int> nums) {
33        kLargest = vector<int>();
34        if(nums.size() > 0){
35            sort(nums.begin(), nums.end());
36            //(nums.size(), k , nums.size()-1-k) = (1, 1, 18446744073709551615)??
37            //push until kLargest has k elements or nums has been iterated
38            for(vector<int>::reverse_iterator rit = nums.rbegin(); rit < nums.rbegin() + k && rit != nums.rend(); rit++){
39                kLargest.push_back(*rit);
40            }
41        }
42        //keep insert 
43        for(int i = kLargest.size(); i < k; i++){
44            kLargest.push_back(INT_MIN);
45        }
46    }
47    
48    int add(int val) {
49        int k = kLargest.size();
50        kLargest.push_back(val);
51        
52        for(int i = 0; i < k; i++){
53            if(val >= kLargest[i]){
54                kLargest.insert(kLargest.begin()+i, val);
55                break;
56            }
57        }
58        kLargest.resize(k);
59        return kLargest[k-1];
60    }
61};
62
63/**
64 * Your KthLargest object will be instantiated and called as such:
65 * KthLargest* obj = new KthLargest(k, nums);
66 * int param_1 = obj->add(val);
67 */
68 
69//https://leetcode.com/problems/kth-largest-element-in-a-stream/discuss/150609/C%2B%2B-super-easy-28ms-solution-beats-100!
70//Runtime: 52 ms, faster than 96.48% of C++ online submissions for Kth Largest Element in a Stream.
71//Memory Usage: 19.5 MB, less than 69.93% of C++ online submissions for Kth Largest Element in a Stream.
72
73/**
74class KthLargest {
75private:
76    priority_queue<int, vector<int>, greater<int>> pq;
77    int myk;
78public:
79    KthLargest(int k, vector<int> nums) {
80        myk = k;
81        for(int e : nums){
82            pq.push(e);
83            //pop the smallest value
84            if(pq.size() > k) pq.pop();
85        }
86    }
87    
88    int add(int val) {
89        pq.push(val);
90        //only retain myK elements in pq
91        if(pq.size() > myk) pq.pop();
92        //toppest is the smallest
93        return pq.top();
94    }
95};
96**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.