Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Binary Search (Iterative)

Easy Acceptance 79.00% Points 20.00

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.

Hints
Hint 1
N/A
Constraints
  • 1 = nums.length = 105
  • -104 = nums[i], target = 104
  • nums is sorted in non-decreasing order
Companies
Amazon
Topics
Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions