↓Skip to main content
  1. LeetCode/

LeetCode 215: Kth Largest Element in an Array

·2 mins· ·
LeetCode Medium Array Divide-and-Conquer Sorting Heap-Priority-Queue
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-29

  • Submissions: Wrong Answer ×3 → Output Limit Exceeded → Accepted ×3

Approach
#

Top-K (Heap Template 1): a min-heap holds the k largest values so far. Push while it is not full; once full, heappushpop, which immediately discards a value smaller than the top and otherwise replaces the top. After the scan the top is the k-th largest, in O(n log k). Alternatively quickselect recurses only into the side containing the answer, O(n) on average.

My Attempts
#

The first three wrote if len(heap) > k: heappop else: heappush: the heap first grew to k + 1 elements, and afterward a new value triggered a pop without being inserted, so the final top was not the k-th largest: [1, 7], k = 1 returned 1 instead of 7. One more left a print (Output Limit Exceeded); heappushpop when len(heap) == k passed.

Solution
#

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        heap = []
        for x in nums:
            if len(heap) < k:
                heapq.heappush(heap, x)
            else:
                heapq.heappushpop(heap, x)
        return heap[0]

Complexity
#

Time O(n log k), space O(k).

Mistakes to Avoid
#

  • Once the heap is full, still process each new value: push it and pop the smallest, never skip it.
  • The size cap is k; testing > k keeps one too many.

Interview Explanation
#

A size-k min-heap holds the k largest values; once full, each new value is pushpopped, so the top, the smallest of those k, is the k-th largest. Time O(n log k); quickselect averages O(n).

Related

LeetCode 347: Top K Frequent Elements
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 note: count first, then take the k most frequent with a size-k heap or a bucket sort indexed by count
LeetCode 105: Construct Binary Tree from Preorder and Inorder Traversal
·2 mins
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 105 note: the first pre-order value is the root, and its position in the in-order tells the left subtree’s size; look positions up in a dictionary for O(n)
LeetCode 973: K Closest Points to Origin
·1 min
LeetCode Medium Array Math Divide-and-Conquer Geometry
LeetCode 973 note: as in Top-K, keep a size-k max-heap (negated distances) holding the k closest points
LeetCode 75: Sort Colors
·2 mins
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 note: the Dutch flag, with 0s left of low and 2s right of high; after swapping a 2 to high, do not advance, since the swapped-in value is unchecked
LeetCode 47: Permutations II
·2 mins
LeetCode Medium Array Backtracking Sorting
LeetCode 47 note: sort first, and within a level skip a value equal to the previous one when the previous one is unused
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group