From 1199825eb388ac6df82df07a0932b97c8a74b7af Mon Sep 17 00:00:00 2001 From: deepshekhardas Date: Mon, 20 Jul 2026 13:22:59 +0530 Subject: [PATCH] fix: add input validation to cyclic_sort to prevent infinite loop --- sorts/cyclic_sort.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sorts/cyclic_sort.py b/sorts/cyclic_sort.py index 9e81291548d4..f3bde7ef799d 100644 --- a/sorts/cyclic_sort.py +++ b/sorts/cyclic_sort.py @@ -19,6 +19,7 @@ def cyclic_sort(nums: list[int]) -> list[int]: :param nums: List of n integers from 1 to n to be sorted. :return: The same list sorted in ascending order. + :raises ValueError: If nums contains non-integer or negative values. Time complexity: O(n), where n is the number of integers in the list. @@ -27,8 +28,15 @@ def cyclic_sort(nums: list[int]) -> list[int]: [] >>> cyclic_sort([3, 5, 2, 1, 4]) [1, 2, 3, 4, 5] + >>> cyclic_sort([3, 5, -2, 1, 4]) + Traceback (most recent call last): + ... + ValueError: All values must be positive integers """ + if any(not isinstance(x, int) or x <= 0 for x in nums): + raise ValueError("All values must be positive integers") + # Perform cyclic sort index = 0 while index < len(nums):