Skip to content

Fix exponential_search recursing forever when the item is below the first element - #15384

Merged
cclauss merged 2 commits into
TheAlgorithms:masterfrom
Darkslayer3324j:fix/exponential-search-recursion
Sep 21, 2026
Merged

cclauss merged 2 commits into
TheAlgorithms:masterfrom
Darkslayer3324j:fix/exponential-search-recursion

Conversation

@Darkslayer3324j

Copy link
Copy Markdown
Contributor

Describe your change

  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.

exponential_search (and binary_search_by_recursion) never terminate when the item is smaller than every element:

>>> exponential_search([0, 5, 7, 10, 15], -3)
RecursionError: maximum recursion depth exceeded
>>> binary_search_by_recursion([0, 5, 7, 10, 15], -1)
RecursionError: maximum recursion depth exceeded

binary_search_by_recursion uses right=-1 to mean "not given" (if right < 0: right = len(...) - 1). When the item is below the first element the recursion legitimately reaches right = midpoint - 1 = -1, which is then mistaken for "not given", right is reset to the last index, and the search starts over forever. The fix makes the sentinel None, which cannot collide with a real index. Nothing else in the repository calls this function.

Doctests for an item below and above the range are added. I also compared both functions with a membership check on 30,000 random sorted lists (lengths 0-15, values -8..8): 0 mismatches after the change.

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues, then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER". (No open issue for this.)

I left "all my own work" unticked on purpose: this change was written with AI assistance (Claude Code, as AGENTS.md invites). I found the problem by fuzzing the functions in searches/ against a membership check, reproduced it, and ran the doctests, ruff check and ruff format on the changed file.

…irst element

binary_search_by_recursion used right=-1 as its 'not given' sentinel, but the
recursion legitimately reaches right=-1 when the item is smaller than every
element, which reset right to len-1 and never terminated. Use None as the
sentinel and add doctests for items below and above the range.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Sep 20, 2026
@TheAlgorithms TheAlgorithms deleted a comment from oga35767-eng Sep 21, 2026
@cclauss

cclauss commented Sep 21, 2026

Copy link
Copy Markdown
Member

@priya-sundaram-dev Is the bug real? If so, is there a way to solve it without making right polymorphic? Should we have an initial check to see if right is less than left? What happens if left is a negative number? What happens if left is a float? What happens if right is a float?

@priya-sundaram-dev priya-sundaram-dev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. The root cause is the right = -1 sentinel: when item is below every element the recursion drives right negative, and if right < 0: right = len - 1 then resets the window, so it never terminates. Switching the sentinel to right: int | None = None and checking if right is None is the clean, idiomatic fix and keeps a real right < 0 (empty/exhausted window) as a genuine base case.

Verified: reproduced the original RecursionError for exponential_search([0, 5, 7, 10, 15], -3); with the patch all 12 doctests pass and a 100k-case fuzz run against membership (lengths 0-10, out-of-range items on both ends) returns correct indices / -1 with no recursion errors. CI green.

LGTM.

@algorithms-keeper algorithms-keeper Bot removed the awaiting reviews This PR is ready to be reviewed label Sep 21, 2026
@cclauss
cclauss merged commit d81528a into TheAlgorithms:master Sep 21, 2026
6 checks passed
@priya-sundaram-dev

Copy link
Copy Markdown
Contributor

Good questions — happy to walk through them now that it's in. 🙂

Is the bug real? Yes. With the old right: int = -1 sentinel, the reset if right < 0: right = len - 1 fires whenever recursion legitimately narrows the window past the left edge. Searching for an item below sorted_collection[0] drives midpoint down to 0, then recurses with right = midpoint - 1 = -1 — which the sentinel re-expands back to the full length instead of terminating. That's the infinite recursion. The None sentinel fixes it because -1 is now an ordinary "one below left" value and the if right < left: return -1 base case can end the search.

Can we avoid making right polymorphic? Yes, and it may read cleaner: keep the recursive core with a plain int right and never let it reset, and do the len - 1 defaulting once in a thin wrapper (or in exponential_search, which is the only caller). That confines the "default to last index" concern to a single spot and keeps the recursion's type flat. int | None is the more common idiom in this repo, though, so either is defensible — I went with it to keep the diff minimal.

Should we add an explicit right < left check? It's already the terminating base case (if right < left: return -1), and that's exactly what stops the recursion now. An extra guard at the top would be redundant.

Negative left? Not guarded, but not reachable through the public API — exponential_search always enters with left = 0 and left only ever grows via midpoint + 1, so it stays non-negative. A hostile direct caller passing a negative left could get wrong results via Python's negative indexing; if we want to be defensive we could assert left >= 0.

Float left/right? Unsupported by design — midpoint = left + (right - left) // 2 stays a float and sorted_collection[midpoint] raises TypeError: list indices must be integers. The int type hints document that contract; enforcing it at runtime would just trade one exception for another.

Happy to open a small follow-up doing the wrapper/core split if you'd prefer that shape over the None sentinel.

@cclauss

cclauss commented Sep 21, 2026

Copy link
Copy Markdown
Member

@priya-sundaram-dev Yes, please create a small follow-up PR doing the wrapper/core split because I would prefer that shape over the None sentinel.

cclauss pushed a commit that referenced this pull request Sep 21, 2026
Follow-up to #15384. Replace the ``right: int | None`` sentinel on the
recursive path with a thin wrapper that defaults ``right`` once, then
delegates to a nested ``_search(left, right)`` core whose indices are
always concrete ints. This matches the wrapper/core shape already used by
``binary_search.py`` and keeps the recursion flat so the window can only
shrink.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants