DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on • Edited on

Kth Largest Element in C++

Why Single-Pass Greedy Fails & When STL sort() is the Right Choice

Today, I tried to solve the Kth Largest Element problem using
single pass optimization + greedy update.

But it didnโ€™t work.

Instead of forcing optimization, I stepped back and used STL sort() โ€” and that taught me an important lesson:

โ Not every problem can be solved with single-pass greedy logic โž

This article explains why, and how to think correctly.

๐Ÿงฉ Problem Statement

Given an array and an integer k, find the kth largest element.

Example:

Input:  [3, 2, 1, 5, 6, 4], k = 2
Output: 5
Enter fullscreen mode Exit fullscreen mode

๐Ÿง My First Thought: Single Pass + Greedy Update

Since many array problems can be solved using:

one loop

constant space

greedy updates

I asked myself:

โ€œCan I track the kth largest element while traversing once?โ€

Attempted Idea (Greedy Thinking)

Keep updating the largest values

Try to maintain kth largest dynamically

โŒ Why This Fails

To find the kth largest, you must know how many elements are larger than the current value.

In a single pass:

You donโ€™t know future elements

You canโ€™t decide rank accurately

Greedy decisions become unreliable

๐Ÿ“Œ Key Insight

Greedy works when local decisions guarantee global correctness.
Kth largest requires global ordering, not local comparison.

โŒ Example Where Greedy Breaks

Array:

{7, 4, 6, 3, 9, 1}
k = 2
Enter fullscreen mode Exit fullscreen mode

While traversing:

You may think 7 is large

Later 9 appears and changes ranking

Earlier greedy decisions become invalid

โžก๏ธ Ranking problems depend on full context, not partial traversal.

๐Ÿง  Important Learning
Problem Type Single Pass Greedy
Max / Min โœ… Works
Second Largest โœ… Works
Stock Buy Sell โœ… Works
Kth Largest โŒ Not reliable
โœ… Correct Approach: Using STL sort()

When a problem requires ordering, sorting is the simplest and safest solution.

C++ Solution Using sort()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> arr = {3, 2, 1, 5, 6, 4};
    int k = 2;

    sort(arr.begin(), arr.end(), greater<int>());

    cout << "Kth largest element: " << arr[k - 1];
}
Enter fullscreen mode Exit fullscreen mode

โฑ Time & Space Complexity
Time Complexity

Sorting: O(n log n)

Space Complexity

In-place sort: O(1) (ignoring recursion stack)

๐Ÿ“Œ This is acceptable in most interview problems unless constraints are huge.

โš ๏ธ But Is Sorting Always the Best?

Not always.

For large data:

priority_queue โ†’ O(n log k)

nth_element โ†’ Average O(n)

But for learning & interviews, sort() is:

readable

reliable

easy to explain

๐Ÿง  Interview Thinking Lesson (Most Important)

When solving a problem, ask:

Does the problem need global ordering?

Can local greedy decisions guarantee correctness?

If answer is โŒ
๐Ÿ‘‰ Donโ€™t force single-pass optimization.

โ Optimization comes after correctness โž

๐Ÿš€ Final Takeaway

Todayโ€™s learning was not about failure โ€” it was about judgment.

I tried greedy โ†’ understood its limits

I used STL โ†’ got correct and clean solution

I learned when NOT to optimize

Thatโ€™s real progress.

๐Ÿ“Practice Suggestion

Try classifying problems like this:

โœ” Greedy single-pass possible?

โœ” Needs sorting?

โœ” Needs heap?

This habit improves interview thinking speed.

Top comments (1)

Collapse
 
charles_kumar_30654e10958 profile image
Charles Kumar

This one really got me

your Space Complexity analysis hints about hidden costs ( Advanced Algorithm Analysis )

In-place sort: O(1) (ignoring recursion stack)

Takeaway :

classifying problems like this quickly shows us the right choice:

โœ” Greedy single-pass possible?

โœ” Needs sorting?

โœ” Needs heap?