Practice: Kth Largest Element in an Array

Problem: https://leetcode.com/problems/kth-largest-element-in-an-array/

Recognition reminder: you want the kth largest value (in sorted order, counting duplicates), not the kth distinct value. This is the size-k heap in its purest form: you never need the whole array sorted, only enough order to name one element. The interesting decision is which kind of heap, and of what size, lets you answer in one pass.

Before you start (the five-beat rhythm)

  1. Your Pattern Card for this week is already written.
  2. Name the pattern aloud and write your approach as a plain-English comment before any code.
  3. Struggle floor: 25 minutes unaided. No hints, no AI, no Discuss tab.
  4. If stuck past the floor, ask the tutor for a hint. Six rungs, one per ask.
  5. Debrief in your commit message before moving to the next problem.

Your target

Fill these in yourself before you look at anyone else’s solution:

Target time complexity:  ____
Target space complexity: ____

Sorting the whole array and indexing the kth-from-the-end is O(n log n) and works, but it does more than the problem asks. The heap question is: if you only want the kth largest, how large a heap do you actually need to carry, and should it be a min-heap or a max-heap so that the element you evict is always the right one? There is also a non-heap method (think back to how a partition step splits an array around a pivot) that beats the heap on average time. Write down the complexity of whichever you implement, and be ready to discuss the other in your debrief.

The function you implement

Write a function find_kth_largest(nums: list[int], k: int) -> int in a file named solution.py in this folder (your own work repo, not the course repo). It returns the kth largest element of nums. As the LeetCode constraints guarantee, 1 <= k <= len(nums), so you do not have to handle an out-of-range k.

Where your code goes

Write your solution in your own work repo (see getting-started.md), not in this folder. This folder ships only the problem spec and a provided-example test (tests/test_provided.py) so you can check the given cases locally before you submit to LeetCode’s judge. The judge is the oracle; the tutor will not confirm your answer by reading it.

Debrief (paste into your commit message)

1. What pattern did this turn out to be?
2. What was the trigger phrase or input shape that should have made me reach for it?
3. What was the time and space complexity, and what would dominate at scale?
4. What edge case would have broken my first attempt?
5. What would I do differently in three days when I see this cold?