TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation · 5.9K subscribers
Post #1392 288
🎯 CODING CHALLENGE #7 - Kth Largest Element in an Array
Difficulty: Medium | Asked at: Facebook, Amazon, Google


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


💡 Hint: Sorting works but is O(n log n). Can you do better with a heap that only ever holds k elements?

Solution (min-heap approach):
python
import heapq

def find_kth_largest(nums, k):
heap = nums[:k]
heapq.heapify(heap)

for num in nums[k:]:
if num > heap[0]:
heapq.heapreplace(heap, num)

return heap[0]


Complexity: O(n log k) time, O(k) space - much better than sorting when k is small relative to n.

Common mistake: Using a max-heap of the FULL array (heapifying all n elements, then popping k times) - this works, but it's a weaker answer. Building a min-heap of just size k and comparing incoming elements against the smallest kept element is the optimization interviewers are hoping to see.

Alternative: Quickselect gets this down to average O(n) time, though worst case O(n²) - a great follow-up to mention if you want to show extra depth.

Do you know Quickselect, or is the heap approach your default here? 👇
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026💼 Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026💼 What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →