Binary Search

LeetCode 704

LeetCode #704Difficulty: EasyNeetCode 150

LeetCode 704: Binary Search

LeetCode

Given an array of integers nums sorted in ascending order, search target in O(log n) runtime.

Problem Description

Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return -1. You must write an algorithm with `O(log n)` runtime complexity.

Examples:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Constraints:
  • 1 <= nums.length <= 10^4
  • nums is sorted in ascending order.

Core Mental Model

Binary Search divides the search domain in half at each step: N -> N/2 -> N/4 -> ... -> 1. Maximum steps required is ceil(log2 N).

Formal Loop Invariant

Invariant: At the beginning of each iteration, if target exists in nums, it must be contained in the closed interval [low, high].

Key Architectural Takeaway:

Binary search applies to any monotonic search space where answers transition from false to true.

Asymptotic Complexity Analysis

Time ComplexityO(log N) Search interval divides by 2 in each iteration.
Space ComplexityO(1) Constant memory.

Bottleneck: Reduces 10^9 operations to ~30 operations.

Edge Cases & Screener Traps

  • Single element array
  • Target absent