Skip to content

Conversation

@sreejabavandla
Copy link

Fix incorrect output for Binary Search when list contains duplicates (Fixes #13840)

Describe your change:

Fixed a bug in the binary search algorithm that caused incorrect output when the list contained duplicate elements.

  • Updated the condition to correctly return the index of the first matching element.
  • Ensured the loop continues searching the left half when a duplicate is found.
  • Verified behavior with lists containing multiple identical values.
  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests?
  • Documentation 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.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All function 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. (Not applicable here)
  • If this pull request resolves one or more open issues then the description above includes the issue number(s) with a closing keyword: "Fixes Incorrect output for Binary Search when list contains duplicates #13840".

@algorithms-keeper algorithms-keeper bot added enhancement This PR modified some existing files awaiting reviews This PR is ready to be reviewed labels Nov 5, 2025
Copy link

@ayushHardeniya ayushHardeniya left a comment

Choose a reason for hiding this comment

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

Hi, I’m just passing by and took a quick look at this change.
The updated logic using the answer variable makes sense and correctly handles finding the first occurrence while avoiding unreachable code and redundant returns.
The structure is clear and consistent with standard binary search patterns.

Overall, this looks correct and well-implemented - nice work improving the clarity here. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect output for Binary Search when list contains duplicates

2 participants