Binary Search Iterative Approach in DSA C# - Time & Space Complexity
We want to understand how the time taken by binary search changes as the list size grows.
Specifically, how many steps does it take to find a number in a sorted list?
Analyze the time complexity of the following code snippet.
public int BinarySearch(int[] arr, int target) {
int left = 0, right = arr.Length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
This code searches for a target number in a sorted array by repeatedly dividing the search range in half.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that halves the search range each time.
- How many times: The loop runs until the search range is empty, roughly halving the range each step.
Each step cuts the search space in half, so the number of steps grows slowly even if the list gets very large.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: Doubling the input size adds only one extra step.
Time Complexity: O(log n)
This means the number of steps grows slowly, increasing by one step each time the list size doubles.
[X] Wrong: "Binary search checks every element one by one, so it is O(n)."
[OK] Correct: Binary search does not check every element; it cuts the search space in half each time, so it takes far fewer steps than checking all elements.
Understanding binary search time complexity shows you can analyze efficient algorithms and explain why they are fast, a key skill in interviews.
"What if the array was not sorted? How would the time complexity of searching change?"
Practice
Binary Search Iterative Approach in a sorted array?Solution
Step 1: Understand binary search goal
Binary search aims to find a target value's position quickly by checking the middle element and narrowing the search range.Step 2: Identify iterative approach
The iterative method uses a loop to repeatedly divide the search interval until the target is found or the interval is empty.Final Answer:
To find the position of a target value efficiently by repeatedly dividing the search interval in half -> Option DQuick Check:
Binary search = efficient target search [OK]
- Confusing binary search with sorting
- Thinking it reverses the array
- Assuming it finds max value
Solution
Step 1: Understand overflow risk
Adding low and high directly can cause integer overflow if values are large.Step 2: Use safe middle calculation
Calculating mid as low + (high - low) / 2 avoids overflow by subtracting before adding.Final Answer:
int mid = low + (high - low) / 2; -> Option AQuick Check:
Safe mid calculation = low + (high - low) / 2 [OK]
- Using (low + high) / 2 causing overflow
- Subtracting incorrectly in mid calculation
- Multiplying indices instead of adding
int[] arr = {2, 4, 6, 8, 10};
int target = 6;
int low = 0, high = arr.Length - 1;
int result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
result = mid;
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
Console.WriteLine(result);Solution
Step 1: Trace the binary search steps
Initial low=0, high=4, mid=2 (element 6). arr[2] == target 6, so result=2 and loop breaks.Step 2: Output the result
Since target found at index 2, Console.WriteLine prints 2.Final Answer:
2 -> Option CQuick Check:
Target 6 found at index 2 [OK]
- Confusing index with value
- Not updating low or high correctly
- Assuming target not found returns 0
int BinarySearch(int[] arr, int target) {
int low = 0, high = arr.Length - 1;
while (low < high) {
int 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;
}Solution
Step 1: Analyze loop condition
The loop uses 'while (low < high)', which misses checking when low equals high, possibly skipping the last element.Step 2: Correct loop condition
Changing to 'while (low <= high)' ensures all elements are checked including when low equals high.Final Answer:
Change while condition to 'while (low <= high)' -> Option AQuick Check:
Loop must include low == high to check all elements [OK]
- Using < instead of <= in loop condition
- Incorrect mid calculation causing overflow
- Wrong update of low or high pointers
Solution
Step 1: Understand duplicates in sorted array
Duplicates mean target can appear multiple times; we want the first index where it appears.Step 2: Modify binary search to find first occurrence
When target found at mid, record mid but continue searching left half (high = mid - 1) to find earlier occurrence.Final Answer:
When target is found, continue searching left half to find earlier occurrence -> Option BQuick Check:
Find first occurrence by searching left after match [OK]
- Stopping search immediately on first match
- Searching right half after finding target
- Switching to linear search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
