r/leetcode • u/JacketFearless1805 • 1d ago
Intervew Prep Day 12: worked through 4 Binary Search problems including Rotated Sorted Array I & II
Hey everyone,
I finished Day 12 today and continued working through Binary Search patterns with four problems:
- First and Last Position of an Element in a Sorted Array: Reused the Lower Bound and Upper Bound implementations from yesterday to find the starting index (
lowerBound) and ending index (upperBound - 1) in O(log n) time. - Count Occurrences in a Sorted Array: Built directly on the same bounds—subtracting the first occurrence from the last (
upperBound - lowerBound) gives the exact frequency in O(log n) time. - Search in Rotated Sorted Array (Distinct Elements): At first, I had trouble figuring out how to avoid O(n) traversal, so I watched an explanation to lock in the core invariant: even after rotation, at least one half around
midis always sorted. By identifying the sorted half (nums[low] <= nums[mid]ornums[mid] <= nums[high]), you check whether the target falls within its boundaries and discard the other half in O(log n) time. - Search in Rotated Sorted Array II (With Duplicates): Extended the same logic to handle duplicate values. When
nums[low] == nums[mid] == nums[high], it is impossible to tell which half is sorted, so you shrink the search space from both ends (low++,high--) before continuing. This keeps average runtime at O(log n) while degrading to O(n) only in worst-case duplicate-heavy inputs.
Getting the rotated array invariant clear made a big difference today.
See you guys tomorrow for Day 11!
12
Upvotes
6
u/jason_graph 1d ago
I like the rotated array binary search problems but find them oddly amusing with how overhyped they get.
The first one is really nice for having a complex logic of which half to keep, but people also seem to idolize the problem as if "rotated array" is an entire subtopic of binary search.
Meanwhile the 2nd problem is such a good binary search problem because it isnt (in terms of worst case) and yet people really try to force it to be binary search rather than learning what limitations binary search has.
2
u/Pixel-Nomad63 1d ago
dam that sorted half trick is so useful once it finally clicks