Menu
CoddyTech

Binary Search

You get a list of integers nums sorted in increasing order, with no value repeated, and an integer target. Return the index of target in nums, counting from 0, or -1 if it is not in the list. Aim for O(log n) time, which means you cannot afford to look at every element.

Function

search(nums: integer-array, target: integer) → integer
numsinteger-array
the sorted list of distinct integers
targetinteger
the value to look for
Returnsinteger
the index of target in nums, or -1 if it is missing

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i], target ≤ 104
  • nums is sorted in strictly increasing order, so every value appears once.

Examples

Input
nums = [-7, -2, 0, 4, 9, 15, 23]target = 9
Output
4
Explanation
nums[4] is 9. The search looks at index 3 (value 4, too small), then index 5 (value 15, too big), then index 4, where it finds 9.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

If nums could repeat values, how would you return the first index of target, still in O(log n)?

Reset code
def search(nums, target):
    # Write code here
Test cases

Case 1

Case 2

Input

nums = [-7, -2, 0, 4, 9, 15, 23]
target = 9

Expected

4