LeetCode ยท #704

Binary Search Solution

Given a sorted array nums and a target, return the index of target or -1 if not found.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #704

๐Ÿ—๏ธ

Pattern

Binary Search โ€” classic

Given a sorted (ascending) integer array nums of n elements and an integer target, write a function to search target in nums. If target exists, return its index. Otherwise return -1.

Example
Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 // 9 exists in nums at index 4
Constraints
โ€ข 1 โ‰ค nums.length โ‰ค 10โด โ€ข -10โด < nums[i], target < 10โด โ€ข All integers in nums are unique โ€ข nums is sorted in ascending order
02
Section Two ยท Approach 1

Linear Scan โ€” O(n)

Walk through every element and check if it equals the target. Correct but ignores the sorted property.

Problem: O(n) scan wastes the sorted guarantee. Binary search halves the search space each step for O(log n).
Java โ€” Linear Scan
class Solution { public int search(int[] nums, int target) { for (int i = 0; i < nums.length; i++) if (nums[i] == target) return i; return -1; } }
Python โ€” Linear Scan
class Solution: def search(self, nums: list[int], target: int) -> int: for i, num in enumerate(nums): if num == target: return i return -1
MetricValue
TimeO(n)
SpaceO(1)
03
Section Three ยท Approach 2

Binary Search โ€” O(log n)

Maintain two pointers left and right. Compute mid. If nums[mid] == target, return mid. If target is smaller, search the left half. If larger, search the right half. Repeat until found or search space is empty.

๐Ÿ’ก Mental model: Think of looking up a word in a dictionary. You don't start at page 1 โ€” you open to the middle. If your word comes before, you flip to the left half's middle. Each flip eliminates half the remaining pages. After ~17 flips you've found any word among 100,000 pages.
Algorithm
  • Step 1: left = 0, right = n - 1.
  • Step 2: While left โ‰ค right: compute mid = left + (right - left) / 2.
  • Step 3: If nums[mid] == target โ†’ return mid.
  • Step 4: If nums[mid] < target โ†’ left = mid + 1.
  • Step 5: If nums[mid] > target โ†’ right = mid - 1.
  • Step 6: If loop ends โ†’ return -1.
๐ŸŽฏ Why left + (right - left) / 2?:
  • Avoids integer overflow that (left + right) / 2 can cause when both are large.
  • In Python this isn't an issue (arbitrary precision), but it's a best practice in Java/C++.
04
Section Four ยท Trace

Visual Walkthrough

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

Binary Search โ€” halve the search space each step
nums = [-1, 0, 3, 5, 9, 12], target = 9 STEP 1: L=0, R=5, mid=2 -1 0 3 5 9 12 L mid R nums[2]=3 < 9 โ†’ search right half, L=3 STEP 2: L=3, R=5, mid=4 -1 0 3 5 9 12 L mid R nums[4]=9 == 9 โ˜… FOUND! Found in 2 steps (logโ‚‚6 โ‰ˆ 2.6). Half the array eliminated each step. Answer: 4 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Binary Search
class Solution { public int search(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } }
Python โ€” Binary Search
class Solution: def search(self, nums: list[int], target: int) -> int: left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return -1
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpaceTrade-off
Linear ScanO(n)O(1)Ignores sorted property
Binary Search โ† optimal O(log n) O(1) Halves search space each step
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Single element[5], target=5L==R==mid==0. Found immediately.
Not found[1,3,5], target=4L crosses R โ†’ return -1.
Target at start[1,2,3], target=1mid goes left โ†’ found at index 0.
Target at end[1,2,3], target=3mid goes right โ†’ found at last index.
โš  Common Mistake: Using left < right instead of left <= right. With strict <, the case where the target is at the last remaining position (L==R) is skipped, causing a miss. Always use โ‰ค for standard find-target binary search.

โ† Back to Binary Search problems