Skip to content

Commit 21b512a

Browse files
author
Pranav
committed
Add input validation to cyclic_sort
1 parent c0db072 commit 21b512a

1 file changed

Lines changed: 17 additions & 2 deletions

File tree

sorts/cyclic_sort.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,26 @@ def cyclic_sort(nums: list[int]) -> list[int]:
2727
[]
2828
>>> cyclic_sort([3, 5, 2, 1, 4])
2929
[1, 2, 3, 4, 5]
30-
"""
30+
>>> cyclic_sort([1, 2, 5])
31+
Traceback (most recent call last):
32+
...
33+
ValueError: All numbers must be in range 1 and 3, got 5.
3134
35+
>>> cyclic_sort([7, 3, 2, 3, 54, 5, 4])
36+
Traceback (most recent call last):
37+
...
38+
ValueError: All numbers must be unique, got [7, 3, 2, 3, 54, 5, 4].
39+
"""
40+
# Reject invalid input to prevent infinite loops and invalid indexing.
41+
n = len(nums)
42+
if len(set(nums)) != n:
43+
raise ValueError(f"All numbers must be unique, got {nums}.")
44+
for num in nums:
45+
if not 1 <= num <= n:
46+
raise ValueError(f"All numbers must be in range 1 and {n}, got {num}.")
3247
# Perform cyclic sort
3348
index = 0
34-
while index < len(nums):
49+
while index < n:
3550
# Calculate the correct index for the current element
3651
correct_index = nums[index] - 1
3752
# If the current element is not at its correct position,

0 commit comments

Comments
 (0)