Skip to main content
Back to problems
Leetcode
Medium
Arrays
Binary Search
Binary Search

Find the index of a target value in a sorted array, or return -1 if it does not exist.

Acceptance 80%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

Problem

Given a sorted array of integers nums in non-decreasing order and an integer target, return the index of target if it exists in the array. Otherwise, return -1.

You should solve this efficiently by narrowing the search space at each step instead of scanning the entire array.

Notes

  • The array is sorted in non-decreasing order.
  • If the target appears multiple times, returning any valid index is acceptable for this classic version.

Input Format

  • nums: an integer array sorted in non-decreasing order
  • target: an integer value to search for

Output Format

  • Return the index of target if found
  • Otherwise return -1

Constraints

  • 0 <= nums.length
  • nums is sorted in non-decreasing order
  • The solution should run in logarithmic time on the size of the array

Hints

  • Repeatedly compare the target with the middle element of the current range.
  • After each comparison, discard the half that cannot contain the target.

Input Format

  • nums: sorted integer array
  • target: integer

Output Format

  • Integer index of target, or -1 if absent

Constraints

  • nums is sorted in non-decreasing order
  • Aim for O(logn)O(\log n) time and O(1)O(1) extra space
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [-1, 0, 3, 5, 9, 12], target = 9

Output

4

Explanation

The value 9 is present at index 4.

Example 2

Input

nums = [-1, 0, 3, 5, 9, 12], target = 2

Output

-1

Explanation

The value 2 does not appear in the array.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.