Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Binary Search (Iterative)

Easy Acceptance 79% Points 20

Given a sorted array of integers and a target value, return the index of the target if it exists in the array. If the target is not present, return -1.

The array is sorted in non-decreasing order. The solution must use the iterative binary search approach, repeatedly dividing the search space in half until the target is found or the search space becomes empty.

Examples
Example 1

Example 1

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

Output: 4

Explanation: The target value 9 exists at index 4 in the array.

Example 2

Example 2

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

Output: -1

Explanation: The target value 2 does not exist in the array, so return -1.

Example 3

Example 3

Input: nums = [1], target = 1

Output: 0

Explanation: The array contains only one element, which matches the target, so return index 0.

Constraints
  • 1 = nums.length = 105
  • -104 = nums[i], target = 104
  • nums is sorted in non-decreasing order
Topics
Binary Search
Companies
Amazon
Added 19 Jul 2026 79% acceptance
Ln 1, Col 1Sign in to save your code
1
1
0