DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted 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 (0)