MEDIUM NC#67 Heap / Priority Queue

215. Kth Largest Element in an Array

๐Ÿ“– Problem

Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Can you solve it without sorting?

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขLevel-order traversal
  • โ€ขQueue discipline
  • โ€ขShortest-step interpretation

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply BFS reasoning pattern
  • โ€ขApply Heap reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use min heap of size k to store k largest elements
  • โ†’ Heap always contains k largest elements seen so far
  • โ†’ Top of heap is kth largest element
  • โ†’ Alternative: QuickSelect for average O(n) time
  • โ†’ Time: O(n log k), Space: O(k)

๐Ÿงญ Prerequisites

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse min heap of size k to store k largest elements
  • โ€ขHeap always contains k largest elements seen so far
  • โ€ขTop of heap is kth largest element

Common Pitfalls

  • โ€ขAlternative: QuickSelect for average O(n) time
  • โ€ขTime: O(n log k), Space: O(k)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
findKthLargest([3,2,1,5,6,4], 2);
Expected:
5
Test Case 2
Not run
Input:
findKthLargest([3,2,3,1,2,4,5,5,6], 4);
Expected:
4
Test Case 3
Not run
Input:
findKthLargest([1], 1);
Expected:
1

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit