Welcome to Day 6 of your coding interview journey.
So far, youβve built a strong toolkit:
- β Day 1: HashMaps
- β Day 2: Sliding Window
- β Day 3: Arrays
- β Day 4: Two Pointers
- β Day 5: Interval Problems
Today, we unlock one of the most powerful and high-frequency techniques:
π Binary Search
π§ What is Binary Search?
Binary Search is an algorithm that works on sorted data and repeatedly divides the search space in half.
π Instead of scanning linearly (O(n)), you jump directly to the answer in:
- β‘ O(log n) time
π When Should You Use It?
Look for these signals:
- Sorted arrays
- βFind targetβ problems
- Min/Max optimization
- Search space reduction
β οΈ But What If the Array is Rotated?
Thatβs where todayβs problem comes in.
π‘ Problem β Search in Rotated Sorted Array
π§© Problem
You are given a sorted array that has been rotated:
nums = [4,5,6,7,0,1,2]
π Find the index of a target value.
If not found, return -1.
β Brute Force
- Linear search
π Time Complexity: O(n)
β Optimal Approach β Modified Binary Search
π§ Key Insight
Even though the array is rotated:
π At least one half is always sorted
So at each step, we:
- Find the middle
- Check which side is sorted
- Decide where to search next
π οΈ Solution in Python
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
# Left half is sorted
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
# Right half is sorted
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
β Example
nums = [4,5,6,7,0,1,2]
target = 0
print(search(nums, target))
Output:
4
π― Step-by-Step Intuition
For:
[4,5,6,7,0,1,2]
- Middle =
7 - Left side
[4,5,6,7]is sorted - Target
0is NOT in this range
π Move right
β‘ Complexity Analysis
- Time:
O(log n) - Space:
O(1)
π₯ Key Pattern
π Identify the sorted half
This trick appears in many variations:
- Find minimum in rotated array
- Search with duplicates
- Peak element problems
β οΈ Common Mistakes
- β Forgetting boundary conditions (
<=vs<) - β Not identifying the sorted half correctly
- β Infinite loops due to pointer mismanagement
- β Mixing up left/right updates
π§ͺ Practice Problems
To master Binary Search, try:
- Find minimum in rotated sorted array
- Search insert position
- First and last position of element
- Peak element
- Median of two sorted arrays
π― Key Takeaways
- Binary Search = logarithmic power
- Always think:
- Is the data sorted?
- Can I divide the search space?
- Learn to adapt it for:
- Rotations
- Conditions
- Edge cases
π Your Challenge (Day 6)
Solve this:
Find the minimum element in a rotated sorted array.
(Hint: use Binary Search π)
π Final Thoughts
Binary Search is one of the highest ROI topics in interviews.
Once you master it, youβll unlock problems that many candidates struggle with.