MediumPro challengePythonJavaScriptTypeScript
Binary Search
AlgorithmsArraysSearch
Implement solve(sorted, target) that searches for target in a sorted
(ascending) array using binary search and returns its index, or -1 if not
found.
Constraints
- O(log n) time — do not use
.indexOfor.find. - Elements are unique numbers.
Sample tests
Test #1Target in the right half
Input: [[1,3,5,7,9],7]
Output: 3
Test #2Target is first element
Input: [[1,3,5,7,9],1]
Output: 0
Test #3Target not present
Input: [[1,3,5,7,9],6]
Output: -1
Test #4Empty array
Input: [[],5]
Output: -1
Test #5Larger array
Input: [[2,4,6,8,10,12,14,16],14]
Output: 6