← Questions

Kth largest element in an array

0
MetaCodingLast asked Feb 2026

A coding interview question asked in Meta's technical phone screen, last asked Feb 2026. It tests heaps, quickselect and sorting.

Given an unsorted integer array nums and an integer k, return the k-th largest element. Duplicates count as separate elements, so in [5, 5, 4] the 2nd largest is 5. Discuss the time and space cost of each approach, and whether you can avoid fully sorting the array.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • find_kth_largest(nums: list[int], k: int) -> int.

Example

nums = [3, 2, 1, 5, 6, 4],          k = 2  ->  5    # descending: 6, 5, ...
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4  ->  4    # descending: 6, 5, 5, 4, ...
nums = [5, 5, 4],                   k = 2  ->  5

Constraints

  • 1 <= len(nums) <= 10^5.
  • -10^9 <= nums[i] <= 10^9.
  • 1 <= k <= len(nums).

Clarifying questions

  • Do duplicates count separately, or is it the k-th largest distinct value?
  • Is k always valid?
  • May I modify the input array?
  • Is the array given all at once, or as a stream?

What a strong answer covers

  • Sorting: O(n log n) time, simple and a fine baseline.
  • A min-heap of size k: push each value and pop when the heap exceeds k; the top is the answer. O(n log k) time, O(k) space, and it works on a stream.
  • Quickselect: partition around a random pivot and continue only into the side that holds index n - k of the ascending order. Expected O(n), worst case O(n^2), O(1) extra space when done in place.
  • Three-way partitioning so that many equal values do not cause quadratic behaviour.
  • Edge cases: k = 1, k = n, all equal values, negative numbers, a single element.

Follow-ups

  • Values arrive as an endless stream and you must answer "k-th largest so far" after each one.
  • How do you make quickselect's worst case linear (median of medians), and is it worth it in practice?
  • Values are small integers in a known range. Can you do better than O(n log k)?
  • Return the k largest elements themselves, in any order.

Where it's asked

  • Meta · Technical phone screen · Last asked Feb 202645 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

heaps · quickselect · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding