Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Heaps & Priority Queues/Top-K Elements

Technique

Quickselect

Partition around a pivot and recurse into the side containing index k, giving expected O(n) for the k-th smallest.

Learn firstTwo Pointers
0%
mastery
0/3 solved
Practise nextTop K Frequent Elements
IdeaPracticePitfalls

Recognise it

The signal

single k-th largest/smallest query on an array

  1. 1Brute force

    Sort O(n log n).

  2. 2The observation

    Sorting both sides: only the side containing k matters.

  3. 3Why it works

    After partition, the pivot sits at its final sorted position.

Reach for it when

  • +k closest points (unordered output)

Not when

  • ×streaming input (heap)
  • ×many queries (sort once)
  • ×adversarial pivots without randomisation

Practice

Next

Top K Frequent Elements

0/3 solved
  • Top K Frequent ElementsAmazon, MetaMedium
  • Kth Largest Element in an ArrayMeta, AmazonMedium
  • K Closest Points to OriginMeta, AmazonMedium

Pitfalls

Misconceptions

  • !quickselect is worst-case linear (only with median-of-medians)
Go deeperresources

Resources

  • Heap visualizerVisuAlgo · tool
  • Heap cheatsheetTech Interview Handbook · article
  • std::priority_queuecppreference · docs
  • Find Median from Data Stream editorialLeetCode · editorial
  • Heaps and Heap SortAbdul Bari · video
TodayReviewPatternsProblems