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 • 513 views
Explain the LRU (Least Recently Used) Cache architecture and how to implement it in O(1) time complexity.
Advanced level • 1 views
How do you design a Distributed API Rate Limiter and what algorithms are commonly employed?
Advanced level • 1 views
What is Dynamic Programming? Compare Memoization (Top-Down) with Tabulation (Bottom-Up) using the 0/1 Knapsack Problem.
Advanced level • 1 views
How do a stack and a queue differ, and where would each be useful?
Easy level • 1 views