📖 Scenario: You have a list of exam scores from students. You want to find the kth largest score to see who scored in the top group.
🎯 Goal: Build a program that uses a max heap to find the kth largest element from a list of numbers.
📋 What You'll Learn
Create a vector called scores with the exact values: 85, 92, 78, 90, 88, 76, 95
Create an integer variable called k and set it to 3
Use a max heap to find the kth largest score
Print the kth largest score using std::cout
💡 Why This Matters
🌍 Real World
Finding the kth largest value is useful in ranking systems, like finding the top scores in exams or competitions.
💼 Career
Understanding heaps and priority queues is important for software roles involving data processing, optimization, and real-time systems.
Progress0 / 4 steps
1
Create the scores vector
Create a std::vector<int> called scores with these exact values: 85, 92, 78, 90, 88, 76, 95
DSA C++
Hint
Use std::vector<int> scores = {85, 92, 78, 90, 88, 76, 95}; to create the vector.
2
Set the value of k
Create an integer variable called k and set it to 3 inside main()
DSA C++
Hint
Write int k = 3; inside main().
3
Use a max heap to find the kth largest element
Use std::priority_queue<int> called maxHeap to store all elements from scores. Then pop from maxHeap exactly k - 1 times to remove the largest elements before the kth largest. Finally, store the top element of maxHeap in an integer variable called kthLargest
DSA C++
Hint
Use std::priority_queue<int> maxHeap; and push all scores. Then pop k - 1 times. Finally, get the top element.
4
Print the kth largest score
Print the value of kthLargest using std::cout followed by a newline
DSA C++
Hint
Use std::cout << kthLargest << std::endl; to print the result.
Practice
(1/5)
1. What is the main idea behind finding the kth largest element using a max heap?
easy
A. Use a hash map to count frequencies and find the kth largest
B. Build a max heap from the array and extract the maximum element k times
C. Sort the array and pick the kth element from the start
D. Build a min heap and extract the minimum element k times
Solution
Step 1: Understand max heap property
A max heap always keeps the largest element at the root, so extracting the root gives the current largest element.
Step 2: Extract max k times
By removing the root k times, the last extracted element is the kth largest.
Final Answer:
Build max heap and extract max k times -> Option B
Quick Check:
Max heap extraction = kth largest element [OK]
Hint: Extract max from max heap k times to get kth largest [OK]
Common Mistakes:
Using min heap instead of max heap
Sorting and picking wrong index
Confusing kth largest with kth smallest
2. Which of the following is the correct C++ syntax to create a max heap from a vector nums in-place?
easy
A. std::priority_queue maxHeap(nums.begin(), nums.end());
B. std::make_heap(nums.begin(), nums.end(), std::greater<int>());
C. std::priority_queue<int> maxHeap(nums.begin(), nums.end());