Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Heap / Priority Queue High frequency Solution Available Practice Mode

Kth Largest Element in an Array LeetCode Solution

Tags: #Array #Heap #Sorting #Quickselect

Approach Summary

Maintain a min-heap of size k. Each new element replaces the min if it is larger. The heap top is the kth largest.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Heap / Priority Queue Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Heap / Priority Queue pattern.

Framework: Heap / Priority Queue • Interview Prep: Tested at FAANG • Explore all Heap / Priority Queue problems & invariants →

How to Recognize This Pattern

  • Find kth largest/smallest
  • Streaming data

Complexity Analysis

Time Complexity

O(n log k)

Space Complexity

O(k)

Tags

Array Heap Sorting Quickselect

Frequently Asked Questions

What is the optimal time and space complexity for Kth Largest Element in an Array?
The optimal solution for Kth Largest Element in an Array achieves O(n log k) runtime complexity and requires O(k) auxiliary space. Each of the n elements does one heap operation costing O(log k) — O(n log k) time. The heap holds exactly k elements — O(k) space.
How do I identify that Kth Largest Element in an Array requires the Heap / Priority Queue pattern?
In technical interviews, look for key problem signals: Find kth largest/smallest; Streaming data. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Heap / Priority Queue strategy.
What critical edge cases must be handled in Kth Largest Element in an Array?
Essential edge cases to verify include: k = 1 — the largest element; k = n — the smallest element; Duplicate values — they occupy separate heap slots and are counted correctly; All elements identical — any of them is the answer. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Kth Largest Element in an Array?
Kth Largest Element in an Array is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon, Apple, Google.
Buy me a coffee
Daily Practice
0/0