Skip to main content

Kth Largest Element in an Array Using Heap (Python) – Two Efficient Approaches

Problem Overview

The task is to find the kth largest element in an unsorted array. Although sorting the array would work, it requires O(n log n) time, which is inefficient for this problem.

Heap-based solutions allow us to optimize this process by partially ordering elements instead of fully sorting the array.


Approach 1: Min-Heap of Size k

This approach maintains a min-heap that stores only the k largest elements seen so far.

Key Idea

  • Use a min-heap
  • Keep heap size limited to k
  • The smallest element in the heap is the kth largest overall

Algorithm Steps

  1. Initialize an empty min-heap
  2. Traverse the array
  3. If heap size is less than k, push the element
  4. Otherwise, push the new element and remove the smallest one
  5. After traversal, the heap root is the answer

Python Code


import heapq
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        min_heap = []

        for num in nums:
            if len(min_heap) < k:
                heapq.heappush(min_heap, num)
            else:
                heapq.heappushpop(min_heap, num)

        return min_heap[0]

Complexity

  • Time: O(n log k)
  • Space: O(k)

Approach 2: Max-Heap Using Negatives

Since Python only provides a min-heap, we can simulate a max-heap by converting all values to their negatives.

Key Idea

  • Negate all array elements
  • Heapify the array
  • Pop elements k-1 times
  • The next popped element (after negation) is the kth largest

Algorithm Steps

  1. Convert all elements to negative
  2. Apply heapify
  3. Pop from heap k-1 times
  4. Pop once more and negate to get the answer

Python Code


import heapq
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        for i in range(len(nums)):
            nums[i] = -nums[i]

        heapq.heapify(nums)

        for _ in range(k - 1):
            heapq.heappop(nums)

        return -heapq.heappop(nums)

Complexity

  • Time: O(n + k log n)
  • Space: O(1) extra

Note that this approach modifies the input array, which may not be ideal in all cases.


Comparison of Both Approaches

Aspect Min-Heap (Size k) Negatives + Heapify
Heap Size k n
Time Complexity O(n log k) O(n + k log n)
Space Complexity O(k) O(1) extra
Input Modified No Yes
Best For Large arrays, small k Quick implementation

Reference Implementations

Complete Python implementations for these heap-based solutions can be found at the following GitHub links:

Both approaches highlight how heaps can efficiently solve selection problems without sorting the entire dataset.

Comments

Popular posts from this blog

LeetCode 88 Explained: Four Approaches, Mistakes, Fixes & the Final Optimal Python Solution

Evolving My Solution to “Merge Sorted Array” A practical, beginner-friendly walkthrough showing four versions of my code (from a naive approach to the optimal in-place two-pointer solution). Includes explanations, complexity and ready-to-paste code. Problem Summary You are given two sorted arrays: nums1 with size m + n (first m are valid) nums2 with size n Goal: Merge nums2 into nums1 in sorted order in-place . Version 1 — Beginner Approach (Extra List) I merged into a new list then copied back. Works, but not in-place and uses extra memory. class Solution: def merge(self, nums1, m, nums2, n): result = [] p1 = 0 p2 = 0 for _ in range(m+n): if p1 >= m: result.extend(nums2[p2:n]) break elif p2 >= n: result.extend(nums1[p1:m]) break elif nu...

Introducing CodeMad: Your Ultimate Universal IDE with Custom Shortcuts

Introducing CodeMad: Your Ultimate Multi-Language IDE with Custom Shortcuts Welcome to the world of CodeMad, your all-in-one Integrated Development Environment (IDE) that simplifies coding and boosts productivity. Developed in Python, CodeMad is designed to make your coding experience smoother and more efficient across a variety of programming languages, including C, C++, Java, Python, and HTML. Whether you're a beginner or an experienced programmer, CodeMad is your go-to tool. In this blog, we'll dive deep into the workings of CodeMad, highlighting its unique features and easy installation process. The Power of Shortcuts CodeMad's intuitive interface is built around a set of powerful keyboard shortcuts that make coding a breeze. Here are some of the key shortcuts you'll find in CodeMad: Copy (Ctrl+C) : Duplicate text with ease. Paste (Ctrl+V) : Quickly insert copied content into your code. Undo (Ctrl+Z) and Redo (Ctrl+Y) : Correct mistakes and s...

Product of Array Except Self in Python | Prefix & Suffix Explained (LeetCode 238)

Problem Overview The Product of Array Except Self is a classic problem that tests your understanding of array traversal and optimization. The task is simple to state but tricky to implement efficiently. Given an integer array nums , you need to return an array such that each element at index i is equal to the product of all the elements in nums except nums[i] . The challenge is that: Division is not allowed The solution must run in O(n) time Initial Thoughts At first glance, it feels natural to compute the total product of the array and divide it by the current element. However, this approach fails because division is forbidden and handling zeroes becomes messy. This pushed me to think differently — instead of excluding the current element, why not multiply everything around it? That’s where the prefix and suffix product pattern comes in. Key Insight: Prefix & Suffix Products For every index i : Prefix product → product of all elements to t...