Binary Search easy
Problem Statement
Given a sorted (in ascending order) integer array nums
of n
integers and a target
integer, 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.
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
Steps & Explanation
The problem requires us to implement a binary search algorithm. Binary search is an efficient algorithm for finding a target value within a sorted array. It works by repeatedly dividing the search interval in half. If the target value is less than the middle element, the search continues in the lower half; otherwise, it continues in the upper half. This process is repeated until the target value is found or the search interval is empty.
Here's a breakdown of the steps:
-
Initialization: Set
left
pointer to 0 (start of the array) andright
pointer tonums.size() - 1
(end of the array). -
Iteration: While
left
is less than or equal toright
:- Calculate the
mid
index:mid = left + (right - left) / 2
. This prevents potential integer overflow issues. - Compare
nums[mid]
withtarget
:- If
nums[mid] == target
, returnmid
(target found). - If
nums[mid] < target
, the target must be in the right half, so updateleft = mid + 1
. - If
nums[mid] > target
, the target must be in the left half, so updateright = mid - 1
.
- If
- Calculate the
-
Target not found: If the loop completes without finding the target, return
-1
.
Code (C++)
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 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;
}
};
Complexity Analysis
- Time Complexity: O(log n) - Binary search halves the search space with each iteration.
- Space Complexity: O(1) - The algorithm uses a constant amount of extra space regardless of the input size. This is because we only use a few variables (
left
,right
,mid
) to track the indices.