Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Sorting algorithms

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Sorting algorithms

Kth Largest Element — Quickselect

advancedlayer B7 · Sorting algorithms5 tests

Return the kth largest element of nums — that is, the element that would sit at index n - k if the array were sorted ascending.

  • This is the kth largest value by position, not the kth distinct value: in [3,2,3,1,2,4,5,5,6] the 4th largest is 4
  • Do not sort the whole array. Use quickselect: partition, then recurse into the one side that can contain the answer — average O(n)
  • Choose the pivot deterministically (median-of-three of the low, middle and high elements) so the result never depends on randomness
  • The input array must not be modified — partition a copy

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen