WorkspaceProblem lab
ALGORITHM VISUALIZER

Kth Largest Element

Opening the interactive workspace…

Understanding Kth Largest Element

Return the kth largest value in nums, counting duplicate values separately. The walkthrough maintains a min-heap containing the largest k values seen so far.

How it works

The smallest value among the retained k largest values is exactly the current kth largest.

Fill a min-heap up to k items. Replace its root only when a larger value arrives, then restore the heap property.

Try an example

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

Output: 5

The two largest values are 6 and 5; the heap root is 5.

Constraints

  • 1–32 integers; 1 ≤ k ≤ nums.length.
  • Duplicate values count toward the rank.
  • The heap is shown in array order: children of i are 2i + 1 and 2i + 2.

Use the simulator

Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.

Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.

Related concepts and complexity