13. Kth Largest Element in an Array

13. Kth Largest Element in an Array

Medium
51.0%
1.5k
arraysortingheap
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend or data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A large-scale marketplace or streaming platform processes millions of items daily and assigns each item a score, such as:

  • product popularity score
  • content engagement score
  • ad ranking score
  • fraud risk score

These scores are stored in an integer array nums. For reporting and ranking, the platform needs to quickly find the k-th largest score without fully sorting the entire dataset, since sorting can be expensive at scale.

This is a common practice coding problem for DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given an integer array nums and an integer k, return the k-th largest element in the array.

The k-th largest element is the element that would appear at index k - 1 if the array were sorted in descending order.

Input Format

  • nums: an array of integers
  • k: an integer representing which largest element to return

Output Format

  • A single integer representing the k-th largest element

Examples

Example 1:

Input: nums = [3, 2, 1, 5, 6, 4] k = 2
Output: 5
Explanation: The sorted order (descending) is [6, 5, 4, 3, 2, 1], so the 2nd largest is 5.

Example 2:

Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] k = 4
Output: 4

Constraints

  • 1 <= nums.length <= 100,000
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= nums.length

Loading editor...

[3,2,1,5,6,4], 2
5

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback