Skip to content

Commit 5af34d3

Browse files
Update algorithms/heap/topklargest/__init__.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent 2bb4e1f commit 5af34d3

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

algorithms/heap/topklargest/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@ def k_largest(nums: List[int], k: int = 3) -> List[int]:
1212
Returns:
1313
list: top k largest elements
1414
"""
15+
# input validation to ensure we don't get unexpected results
16+
if not nums or k <= 0:
17+
return []
18+
19+
# Adjust k if it exceeds the length of nums
20+
k = min(k, len(nums))
21+
1522
# create a minimum heap with the first k elements
1623
min_heap = nums[:k]
1724
heapq.heapify(min_heap)

0 commit comments

Comments
 (0)