From 9755a6132996a0eddd69fe9878f4c1c37aad284a Mon Sep 17 00:00:00 2001 From: Lucas Ma <7184042+pony-maggie@users.noreply.github.com> Date: Mon, 15 Jun 2026 08:02:43 +0800 Subject: [PATCH] fix: handle empty inputs in search algorithms --- searches/exponential_search.py | 9 +++++++++ searches/jump_search.py | 5 +++++ 2 files changed, 14 insertions(+) diff --git a/searches/exponential_search.py b/searches/exponential_search.py index ed09b14e101c..d38137b60415 100644 --- a/searches/exponential_search.py +++ b/searches/exponential_search.py @@ -81,10 +81,19 @@ def exponential_search(sorted_collection: list[int], item: int) -> int: 1 >>> exponential_search([0, 5, 7, 10, 15], 6) -1 + >>> exponential_search([], 1) + -1 + >>> exponential_search([1, 1], -1) + -1 """ if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") + if not sorted_collection: + return -1 + + if sorted_collection[0] > item: + return -1 if sorted_collection[0] == item: return 0 diff --git a/searches/jump_search.py b/searches/jump_search.py index 437faf306bb2..31a453d9b483 100644 --- a/searches/jump_search.py +++ b/searches/jump_search.py @@ -33,9 +33,14 @@ def jump_search[T: Comparable](arr: Sequence[T], item: T) -> int: 10 >>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee") 4 + >>> jump_search([], 1) + -1 """ arr_size = len(arr) + if arr_size == 0: + return -1 + block_size = int(math.sqrt(arr_size)) prev = 0