JavaScriptEasySorting & Searching10 min
Find a value with binary search
Return the index of target in a strictly increasing integer array, or -1 if it is absent. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess halve the remaining sorted search interval.
Input
A JSON object {"array": [...], "target": integer}.
Output
Print one compact JSON value: a zero-based index or -1.
Constraints
0 <= array length <= 10000; values and target are integers between -1000000 and 1000000.
Example
Input
{"array":[1,3,5,8],"target":5}Output
2
Example 2 input
{"array":[1],"target":0}Output
-1
Boundary case: An empty interval means the target is absent
Public test cases (2)
Input
{"array":[1,3,5,8],"target":5}Expected output
2
Input
{"array":[1,3],"target":2}Expected output
-1
Hints (2)
- Compare the target with the middle element
- An empty interval means the target is absent
Target complexity: time O(log(n+1)) · space O(1)
