Binary search
Coding problemEasyAsked in: JPMorgan Chase, Zupee
Given a list of distinct integers sorted from smallest to largest, and a target value, return the position of the target in the list, counting from 0. If the target is not in the list, return -1.
Use the sorted order: each step should halve the part of the list that can still hold the target.
Examples
Example 1
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Example 2
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Example 3
Input: nums = [], target = 7
Output: -1
Constraints
- The list holds between 0 and 100,000 integers
- Values are distinct, sorted ascending, and between -1,000,000,000 and 1,000,000,000
- The target is in the same range
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.
to answer and keep your progress. Reading is free for everyone.