Find the kth-largest array element
Find the kth-largest value in an unsorted integer array without fully sorting the array.
Course progress
Problem 91 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [3, 2, 1, 5, 6, 4]; k = 2
Expected output
5
What is happening?
In descending order the values begin 6, 5. Therefore, the second-largest value is 5; quickselect finds its position without sorting everything.
Solution strategy
Build the right mental model
Translate kth largest to its ascending index, partition like quicksort, and continue only in the side containing that index.
Core concepts
quickselect · partitioning
Complexity
Average time O(n), worst-case time O(n^2), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for kth-largest-element
using System;
class Program
{
static int Partition(int[] numbers, int low, int high)
{
int pivot = numbers[high], write = low;
for (int i = low; i < high; i++)
{
if (numbers[i] > pivot) continue;
int temporary = numbers[i]; numbers[i] = numbers[write]; numbers[write++] = temporary;
}
int saved = numbers[write]; numbers[write] = numbers[high]; numbers[high] = saved;
return write;
}
static int KthLargest(int[] numbers, int k)
{
if (k < 1 || k > numbers.Length) throw new ArgumentOutOfRangeException("k");
int target = numbers.Length - k, low = 0, high = numbers.Length - 1;
while (true)
{
int pivot = Partition(numbers, low, high);
if (pivot == target) return numbers[pivot];
if (pivot < target) low = pivot + 1;
else high = pivot - 1;
}
}
static void Main()
{
Console.WriteLine(KthLargest(new[] { 3, 2, 1, 5, 6, 4 }, 2));
}
}Knowledge check
Questions students often ask
What is the main idea behind find the kth-largest array element?
Translate kth largest to its ascending index, partition like quicksort, and continue only in the side containing that index.
What is the time and space complexity of this solution?
Average time O(n), worst-case time O(n^2), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.