Skip to main content
CodeOath
← All problems

Problem

Binary Search

Easy
  • binary-search

nums is sorted in ascending order and has no repeated values. Return the index of target in it, or -1 if target is not there.

A scan from the left is too slow. The search has to take O(log n) time.

Example 1
Input
nums = [3, 8, 14, 21, 30, 47, 52], target = 30
Output
4
Explanation

30 is stored at index 4.

Example 2
Input
nums = [3, 8, 14, 21, 30, 47, 52], target = 25
Output
-1
Explanation

25 would sit between 21 and 30, but it is not in the array.

Example 3
Input
nums = [], target = 4
Output
-1
Explanation

an empty array holds nothing to find.

Constraints:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i], target <= 10^9
  • nums is sorted in ascending order and its values are distinct

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.