Binary Search as Divide and Conquer in DSA Go - Time & Space Complexity
We want to understand how fast binary search finds a number in a sorted list.
How does the time to find the number change as the list gets bigger?
Analyze the time complexity of the following code snippet.
func binarySearch(arr []int, target int) int {
low, high := 0, len(arr)-1
for low <= high {
mid := low + (high-low)/2
if arr[mid] == target {
return mid
} else if arr[mid] < target {
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}
This code searches for a target number in a sorted list by repeatedly dividing the search range in half.
- Primary operation: Checking the middle element and adjusting the search range.
- How many times: The loop runs until the search range is empty, roughly halving the range each time.
Each step cuts the list size in half, so the number of steps grows slowly as the list grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: Doubling the list size adds only one extra step.
Time Complexity: O(log n)
This means the time to find the target grows slowly, adding just a few more steps even if the list gets much bigger.
[X] Wrong: "Binary search checks every element one by one like linear search."
[OK] Correct: Binary search skips half the list each time, so it does far fewer checks than linear search.
Understanding binary search time helps you explain efficient searching clearly, a key skill in many coding interviews.
"What if the list was not sorted? How would the time complexity of searching change?"
Practice
Binary Search as a divide and conquer algorithm?Solution
Step 1: Understand divide and conquer in binary search
Binary search splits the search space into two halves and discards one half each time.Step 2: Identify the efficiency of halving the search space
By halving the range repeatedly, it quickly narrows down to the target element.Final Answer:
It divides the search range in half each time to find the target efficiently. -> Option CQuick Check:
Divide and conquer means halving search space [OK]
- Thinking binary search checks every element
- Confusing sorting with searching
- Believing binary search adds elements
arr?Solution
Step 1: Identify Go for-loop syntax for binary search
Binary search uses two pointers, left and right, initialized to start and end indices.Step 2: Confirm loop condition and initialization
The loop continues while left <= right, using Go's for syntax with multiple variables.Final Answer:
for left, right := 0, len(arr)-1; left <= right; { } -> Option DQuick Check:
Go for-loop with two vars and condition [OK]
- Using for-loop with single index only
- Using while syntax (not valid in Go)
- Incorrect loop condition like left < right
arr := []int{2, 4, 6, 8, 10}
target := 6
left, right := 0, len(arr)-1
found := false
for left <= right {
mid := left + (right-left)/2
if arr[mid] == target {
found = true
break
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
fmt.Println(found)Solution
Step 1: Trace the binary search steps for target 6
Initial left=0, right=4, mid=2 (arr[2]=6), matches target, so found=true.Step 2: Confirm loop breaks and prints found
Loop breaks immediately after finding target, so prints true.Final Answer:
true -> Option BQuick Check:
Target found at mid index 2 [OK]
- Not updating left or right correctly
- Off-by-one errors in mid calculation
- Assuming output is the target value
arr := []int{1, 3, 5, 7, 9}
target := 4
left, right := 0, len(arr)
for left <= right {
mid := (left + right) / 2
if arr[mid] == target {
fmt.Println("Found")
break
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}Solution
Step 1: Check initialization of right pointer
right is set to len(arr), which is out of valid index range (max index is len(arr)-1).Step 2: Correct right initialization and explain impact
Setting right to len(arr)-1 fixes out-of-range error when accessing arr[mid].Final Answer:
right should be initialized to len(arr)-1, not len(arr) -> Option AQuick Check:
Array indices go from 0 to len(arr)-1 [OK]
- Using len(arr) as index causes runtime error
- Wrong mid calculation formula
- Incorrect loop condition causing infinite loop
arr := []int{1, 2, 2, 2, 3, 4}, how can you modify binary search to find the first occurrence of 2?Solution
Step 1: Understand the problem of duplicates in binary search
Standard binary search returns any occurrence, not necessarily the first.Step 2: Modify search to continue left after finding target
When target found, update result and move right pointer to mid-1 to find earlier occurrence.Final Answer:
After finding 2, continue searching left half to find earlier occurrence -> Option AQuick Check:
Find first occurrence by searching left side after match [OK]
- Stopping at first found occurrence
- Searching right half instead of left
- Using linear search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
