We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Kth Largest Element in an Array

Number: 215

Difficulty: Medium

Paid? No

Companies: Meta, Amazon, Google, Microsoft, LinkedIn, Apple, Bloomberg, Spotify, ServiceNow, Salesforce, Morgan Stanley, ByteDance, Walmart Labs, TikTok, Goldman Sachs, Oracle, Nvidia, Uber, PayPal, Flipkart, Intuit, Coupang, Turing, Adobe, eBay, Yahoo, SAP, Samsung, Deutsche Bank, Netflix, Accenture, Yandex, EPAM Systems, Guidewire, AMD, Pocket Gems


Problem Description

Find the kth largest element in an integer array. Note that it is the kth largest element in the sorted order, not the kth distinct element. The goal is to achieve a solution without fully sorting the array.


Key Insights

  • kth largest element can be converted to finding the element at index n-k if the array were sorted.
  • A min-heap of size k is a practical method to maintain the k largest elements seen so far.
  • The Quickselect algorithm can find the kth largest element in average O(n) time with in-place partitioning.
  • Choose an appropriate method based on performance needs and worst-case scenarios.

Space and Time Complexity

Time Complexity:

  • Min-Heap: O(n log k) by maintaining a heap of size k.
  • Quickselect: Average O(n) but worst-case O(n^2) with poor pivot selection. Space Complexity:
  • Min-Heap: O(k)
  • Quickselect: O(1) additional space with in-place partitioning.

Solution

We can solve the problem using either a min-heap or the Quickselect algorithm.

  1. Min-Heap Approach:

    • Initialize a min-heap with the first k elements.
    • Iterate through the remaining elements; if an element is greater than the heap’s root (the smallest in the heap), replace the root.
    • After processing all elements, the root of the min-heap is the kth largest element.
  2. Quickselect Approach:

    • Choose a pivot and partition the array so that elements larger than the pivot come before it.
    • Determine the position of the pivot; if it matches the index corresponding to the kth largest element, return it.
    • Recurse into the appropriate part of the array.

Key points to consider include maintaining heap size for the first approach and proper pivot selection for the Quickselect approach.


Code Solutions

import heapq

def findKthLargest(nums, k):
    # Create a min-heap with the first k elements
    min_heap = nums[:k]
    heapq.heapify(min_heap)  # O(k) time to build the initial heap
    
    # Process the remaining elements
    for num in nums[k:]:
        # If the current element is larger than the smallest in the heap, replace it
        if num > min_heap[0]:
            heapq.heapreplace(min_heap, num)  # O(log k)
    # The smallest element in the heap is the kth largest overall
    return min_heap[0]

# Example usage:
nums = [3, 2, 1, 5, 6, 4]
k = 2
print(findKthLargest(nums, k))  # Expected output: 5
← Back to All Questions