Microsoft · Question 50 · Binary Search
Find First and Last Position of Element in Sorted Array
Problem
Return the first and last index of the target value.
Approach
Two biased binary searches: one leans left, one leans right.
Time O(logn)Space O(1)
How it works
- 1On a hit, keep searching the biased side.
- 2Two passes give first and last positions.
Sample input / output
Input: 6 5 7 7 8 8 10 8 Output: [3, 4]
Constraints
0 <= nums.length <= 10^5; sorted non-decreasing.
Solution — read it, then walk it
Time O(logn)Space O(1)Loops 2Branches 5Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/26
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