Implement binary search that returns an index or -1 in a sorted ascending array. What are its assumptions?
Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Saved automatically
Model Answer & Deep-Dive Explanation
Maintain a search interval and discard the half that cannot contain the target after each comparison. The input must be sorted according to the same comparison rule used by the search. The example retu s any matching index when duplicates exist; finding the first match requires a lower-bound variant. Empty input correctly retu s -1. Runtime is O(log n) and additional space is O(1). Test targets at both ends, a missing value between elements, duplicates, and an empty array.
Related Questions in Data Structures & Algorithms
How to detect a cycle in a Linked List using Floyd's Cycle-Finding Algorithm?
Intermediate level • 516 views
How do a stack and a queue differ, and where would each be useful?
Easy level • 6 views
When would you choose a hash map instead of an array for lookups?
Easy level • 5 views
How can you find two indices whose values sum to a target in one pass?
Medium level • 5 views
When does breadth-first search find a shortest path, and when is it the wrong choice?
Medium level • 5 views