Binary Search
2 approaches, code in every language
Problem description
You are given an array of integers arr that is arranged in strictly increasing order, together with a value target. Report the 0-based index at which target appears. When the value does not occur anywhere in the array, return -1 instead.
Because the input is already sorted, you should not scan every element. Aim for a logarithmic-time solution that repeatedly narrows the region under consideration by comparing the target against the middle element and discarding the half that cannot contain it.
Example 1
Input: arr = [-2, 0, 3, 5, 9, 12], target = 9
Output: 4
The value 9 is stored at index 4, so that index is returned.
Example 2
Input: arr = [-2, 0, 3, 5, 9, 12], target = 2
Output: -1
No element equals 2, so the search reports -1.
Constraints
1 <= arr.length <= 10^4-10^4 <= arr[i], target <= 10^4arr is sorted in strictly increasing order with unique values
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Survey Marker Lookup is our own problem on the technique behind Binary Search: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free