Optimal Python Solution for Kth Largest Element in an Array (Interview Script)

2025-10-02

The Logic

  • Sorting the entire array does unnecessary work.
  • A heap lets us keep track of only the k largest elements.
  • Use a min heap of size k so the smallest element in the heap is the kth largest overall.

Implementation / Diagram

Key Invariant

The heap always contains the k largest elements seen so far, with the smallest of them at the top.

import heapq

def findKthLargest(nums, k):
    heap = []

    for num in nums:
        heapq.heappush(heap, num)
        if len(heap) > k:
            heapq.heappop(heap)

    return heap[0]
The honest play

You've read the playbook. Now make sure you pass the live OA.

Knowing the patterns isn't the same as solving them under a timer with a proctor watching. StealthCoder is the hedge: an AI overlay invisible during screen share. It reads the problem on screen and surfaces a working solution in under 2 seconds. Built by an engineer who got tired of watching his cohort grind for six months and still get filtered at the OA stage. Works on HackerRank, CodeSignal, CoderPad, and Karat.

Hedge your live OA
Invisible during screen share
Get it