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 = 9Output: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
classSolution {
publicintsearch(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
if (nums[i] == target) return i;
return -1;
}
}
Python โ Linear Scan
classSolution:
defsearch(self, nums: list[int], target: int) -> int:
for i, num in enumerate(nums):
if num == target: return i
return -1
Metric
Value
Time
O(n)
Space
O(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++.
โ 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.