Skip to content

Commit 5f04ce2

Browse files
committed
Reduce Time Complexity and Solve Error.
1 parent 0812762 commit 5f04ce2

1 file changed

Lines changed: 22 additions & 93 deletions

File tree

Lines changed: 22 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -1,117 +1,46 @@
1-
"""
2-
Given an array of integers and an integer k, find the kth largest element in the array.
1+
import heapq
2+
from typing import List, Union
33

4-
https://stackoverflow.com/questions/251781
5-
"""
64

7-
8-
def partition(arr: list[int], low: int, high: int) -> int:
5+
def kth_largest_element(arr: List[Union[int, float, str]], k: int) -> Union[int, float, str]:
96
"""
10-
Partitions list based on the pivot element.
11-
12-
This function rearranges the elements in the input list 'elements' such that
13-
all elements greater than or equal to the chosen pivot are on the right side
14-
of the pivot, and all elements smaller than the pivot are on the left side.
7+
Finds the kth largest element in an array using a heap.
158
169
Args:
17-
arr: The list to be partitioned
18-
low: The lower index of the list
19-
high: The higher index of the list
20-
21-
Returns:
22-
int: The index of pivot element after partitioning
23-
24-
Examples:
25-
>>> partition([3, 1, 4, 5, 9, 2, 6, 5, 3, 5], 0, 9)
26-
4
27-
>>> partition([7, 1, 4, 5, 9, 2, 6, 5, 8], 0, 8)
28-
1
29-
>>> partition(['apple', 'cherry', 'date', 'banana'], 0, 3)
30-
2
31-
>>> partition([3.1, 1.2, 5.6, 4.7], 0, 3)
32-
1
33-
"""
34-
pivot = arr[high]
35-
i = low - 1
36-
for j in range(low, high):
37-
if arr[j] >= pivot:
38-
i += 1
39-
arr[i], arr[j] = arr[j], arr[i]
40-
arr[i + 1], arr[high] = arr[high], arr[i + 1]
41-
return i + 1
42-
43-
44-
def kth_largest_element(arr: list[int], position: int) -> int:
45-
"""
46-
Finds the kth largest element in a list.
47-
Should deliver similar results to:
48-
```python
49-
def kth_largest_element(arr, position):
50-
return sorted(arr)[-position]
51-
```
52-
53-
Args:
54-
nums: The list of numbers.
10+
arr: List of numbers or strings.
5511
k: The position of the desired kth largest element.
5612
5713
Returns:
58-
int: The kth largest element.
14+
The kth largest element.
15+
16+
Raises:
17+
ValueError: If k is invalid or not an integer.
5918
6019
Examples:
61-
>>> kth_largest_element([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 3)
20+
>>> kth_largest_element([3, 1, 4, 1, 5, 9], 2)
6221
5
63-
>>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], 1)
22+
>>> kth_largest_element([9, 7, 5, 3, 1], 1)
6423
9
65-
>>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], -2)
66-
Traceback (most recent call last):
67-
...
68-
ValueError: Invalid value of 'position'
69-
>>> kth_largest_element([9, 1, 3, 6, 7, 9, 8, 4, 2, 4, 9], 110)
70-
Traceback (most recent call last):
71-
...
72-
ValueError: Invalid value of 'position'
73-
>>> kth_largest_element([1, 2, 4, 3, 5, 9, 7, 6, 5, 9, 3], 0)
74-
Traceback (most recent call last):
75-
...
76-
ValueError: Invalid value of 'position'
77-
>>> kth_largest_element(['apple', 'cherry', 'date', 'banana'], 2)
78-
'cherry'
79-
>>> kth_largest_element([3.1, 1.2, 5.6, 4.7,7.9,5,0], 2)
80-
5.6
81-
>>> kth_largest_element([-2, -5, -4, -1], 1)
82-
-1
24+
>>> kth_largest_element([1, 2, 3], 3)
25+
1
8326
>>> kth_largest_element([], 1)
84-
-1
85-
>>> kth_largest_element([3.1, 1.2, 5.6, 4.7, 7.9, 5, 0], 1.5)
8627
Traceback (most recent call last):
8728
...
88-
ValueError: The position should be an integer
89-
>>> kth_largest_element((4, 6, 1, 2), 4)
29+
ValueError: Invalid value of 'k'
30+
>>> kth_largest_element([1, 2, 3], -2)
9031
Traceback (most recent call last):
9132
...
92-
TypeError: 'tuple' object does not support item assignment
33+
ValueError: Invalid value of 'k'
9334
"""
94-
if not arr:
95-
return -1
96-
if not isinstance(position, int):
35+
if not isinstance(k, int):
9736
raise ValueError("The position should be an integer")
98-
if not 1 <= position <= len(arr):
99-
raise ValueError("Invalid value of 'position'")
100-
low, high = 0, len(arr) - 1
101-
while low <= high:
102-
if low > len(arr) - 1 or high < 0:
103-
return -1
104-
pivot_index = partition(arr, low, high)
105-
if pivot_index == position - 1:
106-
return arr[pivot_index]
107-
elif pivot_index > position - 1:
108-
high = pivot_index - 1
109-
else:
110-
low = pivot_index + 1
111-
return -1
37+
if not 1 <= k <= len(arr):
38+
raise ValueError("Invalid value of 'k'")
39+
40+
# Use heapq.nlargest to directly get k largest, then pick the last
41+
return heapq.nlargest(k, arr)[-1]
11242

11343

11444
if __name__ == "__main__":
11545
import doctest
116-
11746
doctest.testmod()

0 commit comments

Comments
 (0)