1. Sort KthLargestSort
Remembers: nothing extra; it sorts the array.
- Sort the array, smallest first.
- The kth largest sits at index
n − k. Return it.
The catch: O(n log n) to put all n values in order, when you only ever read one place.
Problem LeetCode 215. Kth Largest Element in an Array ↗ · NeetCode ↗· The solutions on this page are my own.
Four solutions to LeetCode 215, run step by step next to their Java code. Pick a variant and an array, or type your own, then step through the run.
The problem, step by step
Skip to the visualizer ↓You get an array of numbers and a number k. Picture the array ordered from largest to smallest: the answer is whatever sits at place k.
An integer array nums and an integer k, where k is at least 1 and at most the length of the array. Values can repeat.
One number: the value at place k when the array is ordered from largest to smallest. The value itself, not its position.
[9, 9, 7] the 1st and 2nd largest are both 9, and the 3rd largest is 7. It is the kth largest element, not the kth largest distinct value.k = 1 asks for the maximum, and k equal to the length asks for the minimum.[1, 2, 4, 7, 9, 9], the kth largest sits at index n − k = 6 − 3 = 3, which holds 7.[5] with k = 1 gives 5.[4, 4, 4] gives 4 for any k.[-1, -5, -3] with k = 2 gives -3.[2, 2, 3, 3, 3] with k = 4 gives 2, because the three 3s fill places 1 to 3.Sorting everything answers it, but you only need one place. When k is small, do you have to order the whole array? And can you land on place k without ordering the numbers you will never look at?
The example from above, nums = [7, 2, 9, 4, 9, 1] and k = 3, sketched the way you would draw it in an interview. Each board shows what the approach keeps and how it lands on 7. Then step through all four below.
Remembers: nothing extra; it sorts the array.
n − k. Return it.The catch: O(n log n) to put all n values in order, when you only ever read one place.
Remembers: the k largest values seen so far, smallest on top.
The catch: O(n log k) time and O(k) memory. Great when k is small, but with k close to n it is no better than sorting.
Remembers: the array itself, reordered in place, and the range lo to hi still in play.
n − k. Pick a random pivot in [lo, hi].The catch: O(n) on average, but a run of unlucky pivots makes it O(n²). A random pivot makes that very unlikely. It also reorders your input.
Remembers: one count for every value from min to max.
The catch: O(n + range) time and O(range) memory. Fine for values 1 to 9, hopeless when they span a billion.
| Variant | Time | Worst | Extra space | Changes nums | Best when |
|---|
Related in the Lab PriorityQueue in the Java Collections Field Guide
© 2026 Arman Ajabkhani · armantik.com · Privacy