Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Heap
  • Practice Heap
  • MCQs on Heap
  • Heap Tutorial
  • Binary Heap
  • Building Heap
  • Binomial Heap
  • Fibonacci Heap
  • Heap Sort
  • Heap vs Tree
  • Leftist Heap
  • K-ary Heap
  • Advantages & Disadvantages
Open In App
Next Article:
How to Find the Last Occurrence of an Element in a Set in C++?
Next article icon

C++ Program to Find the K’th largest element in a stream

Last Updated : 25 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an infinite stream of integers, find the k’th largest element at any point of time.
Example: 

Input:
stream[] = {10, 20, 11, 70, 50, 40, 100, 5, …}
k = 3
Output:    {_,   _, 10, 11, 20, 40, 50,  50, …}

Extra space allowed is O(k). 

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

We have discussed different approaches to find k’th largest element in an array in the following posts. 
K’th Smallest/Largest Element in Unsorted Array | Set 1 
K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)
Here we have a stream instead of whole array and we are allowed to store only k elements.

A Simple Solution is to keep an array of size k. The idea is to keep the array sorted so that the k’th largest element can be found in O(1) time (we just need to return first element of array if array is sorted in increasing order) 
How to process a new element of stream? 
For every new element in stream, check if the new element is smaller than current k’th largest element. If yes, then ignore it. If no, then remove the smallest element from array and insert new element in sorted order. Time complexity of processing a new element is O(k).

A Better Solution is to use a Self Balancing Binary Search Tree of size k. The k’th largest element can be found in O(Logk) time. 
How to process a new element of stream? 
For every new element in stream, check if the new element is smaller than current k’th largest element. If yes, then ignore it. If no, then remove the smallest element from the tree and insert new element. Time complexity of processing a new element is O(Logk).

An Efficient Solution is to use Min Heap of size k to store k largest elements of stream. The k’th largest element is always at root and can be found in O(1) time. 
How to process a new element of stream? 
Compare the new element with root of heap. If new element is smaller, then ignore it. Otherwise replace root with new element and call heapify for the root of modified heap. Time complexity of finding the k’th largest element is O(Logk).

CPP




// A C++ program to find k'th
// smallest element in a stream
#include <climits>
#include <iostream>
using namespace std;
 
// Prototype of a utility function
// to swap two integers
void swap(int* x, int* y);
 
// A class for Min Heap
class MinHeap {
    int* harr; // pointer to array of elements in heap
    int capacity; // maximum possible size of min heap
    int heap_size; // Current number of elements in min heap
public:
    MinHeap(int a[], int size); // Constructor
    void buildHeap();
    void MinHeapify(
        int i); // To minheapify subtree rooted with index i
    int parent(int i) { return (i - 1) / 2; }
    int left(int i) { return (2 * i + 1); }
    int right(int i) { return (2 * i + 2); }
    int extractMin(); // extracts root (minimum) element
    int getMin() { return harr[0]; }
 
    // to replace root with new node x and heapify() new
    // root
    void replaceMin(int x)
    {
        harr[0] = x;
        MinHeapify(0);
    }
};
 
MinHeap::MinHeap(int a[], int size)
{
    heap_size = size;
    harr = a; // store address of array
}
 
void MinHeap::buildHeap()
{
    int i = (heap_size - 1) / 2;
    while (i >= 0) {
        MinHeapify(i);
        i--;
    }
}
 
// Method to remove minimum element
// (or root) from min heap
int MinHeap::extractMin()
{
    if (heap_size == 0)
        return INT_MAX;
 
    // Store the minimum value.
    int root = harr[0];
 
    // If there are more than 1 items,
    // move the last item to
    // root and call heapify.
    if (heap_size > 1) {
        harr[0] = harr[heap_size - 1];
        MinHeapify(0);
    }
    heap_size--;
 
    return root;
}
 
// A recursive method to heapify a subtree with root at
// given index This method assumes that the subtrees are
// already heapified
void MinHeap::MinHeapify(int i)
{
    int l = left(i);
    int r = right(i);
    int smallest = i;
    if (l < heap_size && harr[l] < harr[i])
        smallest = l;
    if (r < heap_size && harr[r] < harr[smallest])
        smallest = r;
    if (smallest != i) {
        swap(&harr[i], &harr[smallest]);
        MinHeapify(smallest);
    }
}
 
// A utility function to swap two elements
void swap(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
 
// Function to return k'th largest element from input stream
void kthLargest(int k)
{
    // count is total no. of elements in stream seen so far
    int count = 0, x; // x is for new element
 
    // Create a min heap of size k
    int* arr = new int[k];
    MinHeap mh(arr, k);
 
    while (1) {
        // Take next element from stream
        cout << "Enter next element of stream ";
        cin >> x;
 
        // Nothing much to do for first k-1 elements
        if (count < k - 1) {
            arr[count] = x;
            count++;
        }
 
        else {
            // If this is k'th element, then store it
            // and build the heap created above
            if (count == k - 1) {
                arr[count] = x;
                mh.buildHeap();
            }
 
            else {
                // If next element is greater than
                // k'th largest, then replace the root
                if (x > mh.getMin())
                    mh.replaceMin(x); // replaceMin calls
                                      // heapify()
            }
 
            // Root of heap is k'th largest element
            cout << "K'th largest element is "
                 << mh.getMin() << endl;
            count++;
        }
    }
}
 
// Driver program to test above methods
int main()
{
    int k = 3;
    cout << "K is " << k << endl;
    kthLargest(k);
    return 0;
}
 
 

Output:

K is 3 Enter next element of stream 23 Enter next element of stream 10 Enter next element of stream 15 K'th largest element is 10 Enter next element of stream 70 K'th largest element is 15 Enter next element of stream 5 K'th largest element is 15 Enter next element of stream 80 K'th largest element is 23 Enter next element of stream 100 K'th largest element is 70 Enter next element of stream CTRL + C pressed

Time Complexity: O(N * log K)
Auxiliary Space: O(K)

Implementation using Priority Queue:

CPP




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
vector<int> kthLargest(int k, int arr[], int n)
{
    vector<int> ans(n);
 
    // Creating a min-heap using priority queue
    priority_queue<int, vector<int>, greater<int> > pq;
 
    // Iterating through each element
    for (int i = 0; i < n; i++) {
        // If size of priority
        // queue is less than k
        if (pq.size() < k)
            pq.push(arr[i]);
        else {
            if (arr[i] > pq.top()) {
                pq.pop();
                pq.push(arr[i]);
            }
        }
 
        // If size is less than k
        if (pq.size() < k)
            ans[i] = -1;
        else
            ans[i] = pq.top();
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    int n = 6;
    int arr[n] = { 1, 2, 3, 4, 5, 6 };
    int k = 4;
   
    // Function call
    vector<int> v = kthLargest(k, arr, n);
    for (auto it : v)
        cout << it << " ";
    return 0;
}
 
 
Output
-1 -1 -1 1 2 3 

Time Complexity: O(N * log K)
Auxiliary Space: O(K)

Please refer complete article on K’th largest element in a stream for more details!



Next Article
How to Find the Last Occurrence of an Element in a Set in C++?
author
kartik
Improve
Article Tags :
  • Arrays
  • Binary Search Tree
  • C++
  • C++ Programs
  • DSA
  • Heap
  • Searching
  • Amazon
  • array-stream
  • Cisco
  • Order-Statistics
Practice Tags :
  • Amazon
  • Cisco
  • CPP
  • Arrays
  • Binary Search Tree
  • Heap
  • Searching

Similar Reads

  • C++ Program to Find the Second Largest Element in an Array
    In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
    3 min read
  • C++ Program to Find Largest Element in an Array
    In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array. Recommended PracticeHelp a Thief!!!Try It! One of the most simplest and basic approaches to fin
    2 min read
  • C++ Program to Find the K-th Largest Sum Contiguous Subarray
    Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples:  Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the
    3 min read
  • How to Find the Maximum Element in a List in C++?
    In C++, a list is a sequence container provided by the STL library that represents a doubly linked list and allows us to store data in non-contiguous memory locations efficiently. In this article, we will learn how to find the maximum element in a list in C++. Example: Input: myList = {30, 20, 10, 5
    2 min read
  • How to Find the Last Occurrence of an Element in a Set in C++?
    In C++, a set is a container that stores unique elements in a sorted order and elements are accessed and traversed using iterators. In this article, we will learn how to find the last occurrence of a specific element in a set in C++. Example Input:set<int> s = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Key
    2 min read
  • How to Find the Minimum Element in a List in C++?
    In C++, a list is a sequence container provided by the STL library that stores data in non-contiguous memory locations efficiently. In this article, we will learn how to find the minimum element in a list in C++. Example: Input: myList = {30, 10, 20, 50, 40};Output: The minimum element in the list i
    2 min read
  • How to Find the Mode of All Elements in a List in C++?
    In C++, a list is a sequence container used to store data of similar type in non-contiguous memory locations. The mode of a list represents the element that occurs most frequently in the container. In this article, we will learn how to find the mode of a list in C++. Example: Input:myList = {1, 2, 3
    2 min read
  • How to find the Entry with largest Value in a C++ Map
    Given a map in C++, the task is to find the entry in this map with the highest value. Examples: Input: Map = {ABC = 10, DEF = 30, XYZ = 20} Output: DEF = 30 Input: Map = {1 = 40, 2 = 30, 3 = 60} Output: 3 = 60 Approach Iterate the map entry by entry with help of iteratorsmap::iterator itr; for (itr
    2 min read
  • C++ Program to Find Largest Among Three Numbers
    Given three numbers, the task is to find the largest number among them in C++. Examples Input: a = 1, b = 2, c = 11Output: 11Explanation: Since 11 is the largest number among all numbers. Input: a = 9, b = 7, c = 5Output: 9Explanation: Since 9 is the largest number among all numbers. Find Largest Am
    4 min read
  • Given an array and two integers l and r, find the kth largest element in the range [l, r]
    Given an unsorted array arr[] of n integers and an integer k, the task is to find the kth largest element in the given index range [l, r]Examples: Input: arr[] = {5, 3, 2, 4, 1}, k = 4, l = 1, r = 5 Output: 4 4 will be the 4th element when arr[0...4] is sorted.Input: arr[] = {1, 4, 2, 3, 5, 7, 6}, k
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences