11. Kth Largest Element in an Array
mediumAsked at RedisFind the kth largest value; Redis interviewers use it to probe heap intuition that mirrors how ZSETs maintain top-K rankings.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums and an integer k, return the kth largest element. Note this is the kth largest in sorted order, not the kth distinct element.
Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Examples
Example 1
nums = [3,2,1,5,6,4], k = 25Example 2
nums = [3,2,3,1,2,4,5,5,6], k = 44Approaches
1. Sort then index
Sort descending and return nums[k-1].
- Time
- O(n log n)
- Space
- O(1)
nums.sort((a, b) => b - a);
return nums[k - 1];Tradeoff:
2. Min-heap of size k
Push the first k elements then for each remaining replace the heap root when bigger. Final root is the kth largest. This mirrors how ZADD + ZREMRANGEBYRANK keeps a top-K leaderboard.
- Time
- O(n log k)
- Space
- O(k)
function findKthLargest(nums, k) {
const heap = new MinHeap();
for (const n of nums) {
heap.push(n);
if (heap.size() > k) heap.pop();
}
return heap.peek();
}Tradeoff:
Redis-specific tips
Redis values the heap-of-size-k framing because it's exactly how ZSETs cap a top-K leaderboard with ZADD + ZREMRANGEBYRANK; reference that pattern explicitly.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Kth Largest Element in an Array and other Redis interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →