AlgoLounge

Binary Search

easy

Given a sorted (ascending) array of distinct integers nums and an integer target, return the index of target in nums, or -1 if it is not present.

Your algorithm must run in O(log n) time.

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

Constraints

  • 1 <= nums.length <= 10⁴
  • -10⁴ < nums[i], target < 10⁴
  • All integers in nums are unique and sorted in ascending order.
TypeScript
Loading editor…
List of test cases (7)
Case 1
nums = [-1,0,3,5,9,12]
target = 9
Case 2
nums = [-1,0,3,5,9,12]
target = 2
Case 3
nums = [5]
target = 5
Case 4
nums = [5]
target = -5
Case 5
nums = [1,2]
target = 2
Case 6
nums = [-1,0,3,5,9,12]
target = -1
Case 7
nums = [-1,0,3,5,9,12]
target = 12