Binary Search #
- The classic way to write binary search. Three points to note:
- The loop exit condition: note that it is low <= high, not low < high.
- The value of mid: mid := low + (high-low)»1
- Updating low and high. low = mid + 1, high = mid - 1.
func binarySearchMatrix(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)>>1
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
- Variant ways to write binary search. There are 4 basic variants:
- Find the first element equal to target, time complexity O(logn)
- Find the last element equal to target, time complexity O(logn)
- Find the first element greater than or equal to target, time complexity O(logn)
- Find the last element less than or equal to target, time complexity O(logn)
// Binary search for the first element equal to target, time complexity O(logn)
func searchFirstEqualElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] > target {
high = mid - 1
} else if nums[mid] < target {
low = mid + 1
} else {
if (mid == 0) || (nums[mid-1] != target) { // Found the first element equal to target
return mid
}
high = mid - 1
}
}
return -1
}
// Binary search for the last element equal to target, time complexity O(logn)
func searchLastEqualElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] > target {
high = mid - 1
} else if nums[mid] < target {
low = mid + 1
} else {
if (mid == len(nums)-1) || (nums[mid+1] != target) { // Found the last element equal to target
return mid
}
low = mid + 1
}
}
return -1
}
// Binary search for the first element greater than or equal to target, time complexity O(logn)
func searchFirstGreaterElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] >= target {
if (mid == 0) || (nums[mid-1] < target) { // Found the first element greater than or equal to target
return mid
}
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// Binary search for the last element less than or equal to target, time complexity O(logn)
func searchLastLessElement(nums []int, target int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + ((high - low) >> 1)
if nums[mid] <= target {
if (mid == len(nums)-1) || (nums[mid+1] > target) { // Found the last element less than or equal to target
return mid
}
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}
- Use binary search in an almost sorted array. The classic solution works, and variant forms can also be used. Common problem types include finding the peak in a mountain array and finding the dividing point in a rotated sorted array. Problem 33, Problem 81, Problem 153, Problem 154, Problem 162, Problem 852
func peakIndexInMountainArray(A []int) int {
low, high := 0, len(A)-1
for low < high {
mid := low + (high-low)>>1
// If mid is larger, there is a peak on the left, high = m; if mid + 1 is larger, there is a peak on the right, low = mid + 1
if A[mid] > A[mid+1] {
high = mid
} else {
low = mid + 1
}
}
return low
}
- max-min maximum-value minimization problem. Find the maximum value when the condition is minimally satisfied. Problem 410, Problem 875, Problem 1011, Problem 1283.
| No. | Title | Solution | Difficulty | TimeComplexity | SpaceComplexity | Favorite | Acceptance |
|---|---|---|---|---|---|---|---|
| 0004 | Median of Two Sorted Arrays | Go | Hard | 36.2% | |||
| 0033 | Search in Rotated Sorted Array | Go | Medium | 39.0% | |||
| 0034 | Find First and Last Position of Element in Sorted Array | Go | Medium | 41.9% | |||
| 0035 | Search Insert Position | Go | Easy | 43.4% | |||
| 0069 | Sqrt(x) | Go | Easy | O(log n) | O(1) | 37.4% | |
| 0074 | Search a 2D Matrix | Go | Medium | 47.7% | |||
| 0081 | Search in Rotated Sorted Array II | Go | Medium | 35.7% | |||
| 0153 | Find Minimum in Rotated Sorted Array | Go | Medium | 48.9% | |||
| 0154 | Find Minimum in Rotated Sorted Array II | Go | Hard | 43.5% | |||
| 0162 | Find Peak Element | Go | Medium | 46.0% | |||
| 0167 | Two Sum II - Input Array Is Sorted | Go | Medium | O(n) | O(1) | 60.0% | |
| 0209 | Minimum Size Subarray Sum | Go | Medium | O(n) | O(1) | 45.0% | |
| 0222 | Count Complete Tree Nodes | Go | Medium | O(n) | O(1) | 60.6% | |
| 0240 | Search a 2D Matrix II | Go | Medium | 51.0% | |||
| 0268 | Missing Number | Go | Easy | 62.6% | |||
| 0275 | H-Index II | Go | Medium | 37.5% | |||
| 0278 | First Bad Version | Go | Easy | 43.3% | |||
| 0287 | Find the Duplicate Number | Go | Medium | O(n) | O(1) | ❤️ | 59.1% |
| 0300 | Longest Increasing Subsequence | Go | Medium | O(n log n) | O(n) | 52.2% | |
| 0315 | Count of Smaller Numbers After Self | Go | Hard | 42.6% | |||
| 0327 | Count of Range Sum | Go | Hard | 35.8% | |||
| 0349 | Intersection of Two Arrays | Go | Easy | O(n) | O(n) | 70.9% | |
| 0350 | Intersection of Two Arrays II | Go | Easy | O(n) | O(n) | 56.0% | |
| 0352 | Data Stream as Disjoint Intervals | Go | Hard | 59.7% | |||
| 0354 | Russian Doll Envelopes | Go | Hard | 37.9% | |||
| 0367 | Valid Perfect Square | Go | Easy | 43.3% | |||
| 0374 | Guess Number Higher or Lower | Go | Easy | 51.9% | |||
| 0378 | Kth Smallest Element in a Sorted Matrix | Go | Medium | 61.8% | |||
| 0400 | Nth Digit | Go | Medium | 34.1% | |||
| 0410 | Split Array Largest Sum | Go | Hard | 53.5% | |||
| 0436 | Find Right Interval | Go | Medium | 50.8% | |||
| 0441 | Arranging Coins | Go | Easy | 46.2% | |||
| 0456 | 132 Pattern | Go | Medium | 32.4% | |||
| 0475 | Heaters | Go | Medium | 36.5% | |||
| 0483 | Smallest Good Base | Go | Hard | 38.8% | |||
| 0493 | Reverse Pairs | Go | Hard | 30.9% | |||
| 0497 | Random Point in Non-overlapping Rectangles | Go | Medium | 39.4% | |||
| 0528 | Random Pick with Weight | Go | Medium | 46.1% | |||
| 0532 | K-diff Pairs in an Array | Go | Medium | 41.2% | |||
| 0540 | Single Element in a Sorted Array | Go | Medium | 59.1% | |||
| 0611 | Valid Triangle Number | Go | Medium | 50.6% | |||
| 0633 | Sum of Square Numbers | Go | Medium | 34.4% | |||
| 0658 | Find K Closest Elements | Go | Medium | 46.8% | |||
| 0668 | Kth Smallest Number in Multiplication Table | Go | Hard | 51.4% | |||
| 0704 | Binary Search | Go | Easy | 56.1% | |||
| 0710 | Random Pick with Blacklist | Go | Hard | O(n) | O(n) | 33.5% | |
| 0718 | Maximum Length of Repeated Subarray | Go | Medium | 51.3% | |||
| 0719 | Find K-th Smallest Pair Distance | Go | Hard | 36.7% | |||
| 0729 | My Calendar I | Go | Medium | 56.8% | |||
| 0732 | My Calendar III | Go | Hard | 71.5% | |||
| 0744 | Find Smallest Letter Greater Than Target | Go | Easy | 45.8% | |||
| 0778 | Swim in Rising Water | Go | Hard | 59.8% | |||
| 0786 | K-th Smallest Prime Fraction | Go | Medium | 51.7% | |||
| 0793 | Preimage Size of Factorial Zeroes Function | Go | Hard | 43.2% | |||
| 0825 | Friends Of Appropriate Ages | Go | Medium | 46.3% | |||
| 0826 | Most Profit Assigning Work | Go | Medium | 44.9% | |||
| 0852 | Peak Index in a Mountain Array | Go | Medium | 69.0% | |||
| 0862 | Shortest Subarray with Sum at Least K | Go | Hard | 26.0% | |||
| 0875 | Koko Eating Bananas | Go | Medium | 52.1% | |||
| 0878 | Nth Magical Number | Go | Hard | 35.4% | |||
| 0887 | Super Egg Drop | Go | Hard | 27.1% | |||
| 0888 | Fair Candy Swap | Go | Easy | 60.7% | |||
| 0911 | Online Election | Go | Medium | 52.2% | |||
| 0981 | Time Based Key-Value Store | Go | Medium | 52.2% | |||
| 1004 | Max Consecutive Ones III | Go | Medium | 63.2% | |||
| 1011 | Capacity To Ship Packages Within D Days | Go | Medium | 67.7% | |||
| 1157 | Online Majority Element In Subarray | Go | Hard | 41.8% | |||
| 1170 | Compare Strings by Frequency of the Smallest Character | Go | Medium | 61.5% | |||
| 1201 | Ugly Number III | Go | Medium | 28.9% | |||
| 1208 | Get Equal Substrings Within Budget | Go | Medium | 48.6% | |||
| 1235 | Maximum Profit in Job Scheduling | Go | Hard | 53.4% | |||
| 1283 | Find the Smallest Divisor Given a Threshold | Go | Medium | 56.2% | |||
| 1300 | Sum of Mutated Array Closest to Target | Go | Medium | 43.6% | |||
| 1337 | The K Weakest Rows in a Matrix | Go | Easy | 72.1% | |||
| 1385 | Find the Distance Value Between Two Arrays | Go | Easy | 66.6% | |||
| 1439 | Find the Kth Smallest Sum of a Matrix With Sorted Rows | Go | Hard | 61.4% | |||
| 1482 | Minimum Number of Days to Make m Bouquets | Go | Medium | 54.0% | |||
| 1539 | Kth Missing Positive Number | Go | Easy | 58.6% | |||
| 1608 | Special Array With X Elements Greater Than or Equal X | Go | Easy | 60.5% | |||
| 1631 | Path With Minimum Effort | Go | Medium | 55.7% | |||
| 1648 | Sell Diminishing-Valued Colored Balls | Go | Medium | 30.4% | |||
| 1649 | Create Sorted Array through Instructions | Go | Hard | 37.5% | |||
| 1658 | Minimum Operations to Reduce X to Zero | Go | Medium | 37.6% | |||
| 1818 | Minimum Absolute Sum Difference | Go | Medium | 30.4% |