Microsoft · Question 46 · Binary Search
Binary Search
Problem
Given a sorted array and a target value, return the index if found, else -1.
Approach
Halve the search range by comparing the middle.
Time O(logn)Space O(1)
How it works
- 1Compare the middle element.
- 2Discard the half that cannot hold the target.
Sample input / output
Input: 6 -1 0 3 5 9 12 9 Output: 4
Constraints
1 <= nums.length <= 10^4; sorted distinct; -10^4 <= target <= 10^4.
Solution — read it, then walk it
Time O(logn)Space O(1)Loops 2Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/18
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits