Problem 704: Binary Search
Question
LeetCode Link | 704. Binary Search | Easy
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.
Constrains
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.
Examples
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
Solution Approach
Method: Binary Search
Constrains
- Sorted list
- Unique values
The premise of this problem is that the array is sorted, and the problem also emphasizes that there are no duplicate elements in the array, because if there are duplicate elements, the index of the element returned by the binary search may not be unique. These are the prerequisites for using binary search. When you see that the problem description meets the above conditions, you might want to consider whether binary search can be used.
Concept Explanation
We define the target to be within a closed interval, specifically [left, right]. The definition of the interval determines how the binary search code should be written. Because the target is defined to be within the [left, right] interval, there are the following two points:
- Use
while (left <= right)
with<=
, becauseleft == right
is meaningful, so we use<=
. - If
nums[middle] > target
, assignright = middle - 1
, because the currentnums[middle]
is definitely not the target. Therefore, the next search should end atmiddle - 1
for the left interval.
Code
- Time complexity: O(log n)
- Space complexity: O(1)
TypeScript
1 | function search(nums: number[], target: number): number { |
Conclusion
Binary search is a very important fundamental algorithm. Just remember that it requires a ordered/sorted array and all values must be unique in array. Have a clear understanding of the intervals in array should be good enough to write binary search.