DSAPrep
EasyBinary Search

Binary Search

Given an array of integers nums which is sorted in ascending order, and an integer target, search for target in nums. If it exists, return its index; otherwise return -1.

You must write an algorithm with O(log n) runtime complexity.

Example 1

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4.

Example 2

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All the integers in nums are unique.
  • nums is sorted in ascending order.
View original on LeetCode β†—

Linear Scan

Time O(n)Space O(1)

The obvious approach: check every element until you find the target. It’s correct, but it completely ignores the one piece of extra information the problem hands you for free β€” the array is sorted β€” which is exactly what the O(log n) requirement is hinting you should exploit.

class Solution:
def search(self, nums: list[int], target: int) -> int:
for i, num in enumerate(nums):
if num == target:
return i
return -1

Binary Search

OptimalTime O(log n)Space O(1)

Because the array is sorted, checking the middle element tells you which half the target must be in (if it’s present at all) β€” so you can discard the other half entirely, every time. Repeat on the shrinking window until you find the target or the window is empty.

class Solution:
def search(self, nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1

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

lo
-1
0
0
1
mid
3
2
5
3
9
4
hi
12
5
lo = 0mid = 2hi = 5
1 / 3
comparingseenresultdiscarded

mid=2 β†’ nums[2]=3 < 9, target is to the right. Discard indices 0-2, set lo = mid+1.

Why it’s correct: sortedness guarantees that if nums[mid] < target, every index ≀ mid is also < target and can be safely discarded (symmetric argument for >). No valid answer is ever thrown away. Complexity: the search window halves every iteration, so after k steps only n / 2^k elements remain β€” reaching a single element takes k = logβ‚‚ n steps β†’ O(log n) time, O(1) space.