Skip to content

Commit 71d1484

Browse files
committed
feat: implement quick select in kth largest element in an array
1 parent 5a9562c commit 71d1484

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

alternative/medium/kth_largest_element_in_an_array.py

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from typing import List
22
import heapq
33

4+
# Algorithm - Max Heap
5+
# Time Complexity - O(nlogn)
6+
# Space Complexity - O(n)
47
def findKthLargest(nums: List[int], k: int) -> int:
58
max_heap = []
69

@@ -13,9 +16,36 @@ def findKthLargest(nums: List[int], k: int) -> int:
1316

1417
return -heapq.heappop(max_heap)
1518

16-
# Algorithm - Max Heap
17-
# Time Complexity - O(nlogn)
18-
# Space Complexity - O(n)
19+
# Algorithm - Quick Select
20+
# Time Complexity - O(n)
21+
# Space Complexity - O(1)
22+
def findKthLargestV2(nums: List[int], k: int) -> int:
23+
k = len(nums) - k
24+
left, right = 0, len(nums) - 1
1925

26+
while left < right:
27+
pivot = partition(nums, left, right)
28+
if pivot < k:
29+
left = pivot + 1
30+
elif pivot > k:
31+
right = pivot - 1
32+
else:
33+
break
34+
35+
return nums[k]
36+
37+
def partition(nums: List[int], left: int, right: int) -> int:
38+
pivot = left
39+
for i in range(left, right):
40+
if nums[i] <= nums[right]:
41+
nums[i], nums[pivot] = nums[pivot], nums[i]
42+
pivot += 1
43+
44+
nums[pivot], nums[right] = nums[right], nums[pivot]
45+
46+
return pivot
47+
2048
assert findKthLargest([3,2,1,5,6,4], 2) == 5
21-
assert findKthLargest([3,2,3,1,2,4,5,5,6], 4) == 4
49+
assert findKthLargestV2([3,2,1,5,6,4], 2) == 5
50+
assert findKthLargest([3,2,3,1,2,4,5,5,6], 4) == 4
51+
assert findKthLargestV2([3,2,3,1,2,4,5,5,6], 4) == 4

0 commit comments

Comments
 (0)