Skip to content

Update kth-largest-element-in-an-array.py #198

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Python/kth-largest-element-in-an-array.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,21 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums):
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx

"""
This implementation maintains a min-heap of size k, ensuring that the smallest element in the heap is the k-th largest in the array.
The time complexity is O(Nlogk), which is efficient for large arrays.
"""

import heapq
class Solution3(object):
def findKthLargest(self, nums: List[int], k: int) -> int:
# Create a min-heap with the first k elements
min_heap = nums[:k]
heapq.heapify(min_heap)

# Iterate through the remaining elements
for num in nums[k:]:
if num > min_heap[0]: # Compare with the smallest element in the heap
heapq.heappushpop(min_heap, num) # Push new element and pop the smallest

return min_heap[0] # The root of the heap is the k-th largest element