Bird
Raised Fist0
DSA C#programming~5 mins

Binary Search Iterative Approach in DSA C# - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Binary Search Iterative Approach
O(log n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10About 4 steps
100About 7 steps
1000About 10 steps

Pattern observation: Doubling the input size adds only one extra step.

Final Time Complexity

Time Complexity: O(log n)

This means the number of steps grows slowly, increasing by one step each time the list size doubles.

Common Mistake

[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.

Interview Connect

Understanding binary search time complexity shows you can analyze efficient algorithms and explain why they are fast, a key skill in interviews.

Self-Check

"What if the array was not sorted? How would the time complexity of searching change?"

Practice

(1/5)
1. What is the main purpose of the Binary Search Iterative Approach in a sorted array?
easy
A. To find the maximum value in the array
B. To sort the array elements in ascending order
C. To reverse the array elements
D. To find the position of a target value efficiently by repeatedly dividing the search interval in half

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    To find the position of a target value efficiently by repeatedly dividing the search interval in half -> Option D
  4. Quick Check:

    Binary search = efficient target search [OK]
Hint: Binary search halves the search space each step [OK]
Common Mistakes:
  • Confusing binary search with sorting
  • Thinking it reverses the array
  • Assuming it finds max value
2. Which of the following is the correct way to calculate the middle index in an iterative binary search in C# to avoid overflow?
easy
A. int mid = low + (high - low) / 2;
B. int mid = (low + high) / 2;
C. int mid = (low - high) / 2;
D. int mid = (low * high) / 2;

Solution

  1. Step 1: Understand overflow risk

    Adding low and high directly can cause integer overflow if values are large.
  2. Step 2: Use safe middle calculation

    Calculating mid as low + (high - low) / 2 avoids overflow by subtracting before adding.
  3. Final Answer:

    int mid = low + (high - low) / 2; -> Option A
  4. Quick Check:

    Safe mid calculation = low + (high - low) / 2 [OK]
Hint: Use low + (high - low) / 2 to prevent overflow [OK]
Common Mistakes:
  • Using (low + high) / 2 causing overflow
  • Subtracting incorrectly in mid calculation
  • Multiplying indices instead of adding
3. What will be the output of the following C# code snippet?
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);
medium
A. -1
B. 3
C. 2
D. 0

Solution

  1. 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.
  2. Step 2: Output the result

    Since target found at index 2, Console.WriteLine prints 2.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    Target 6 found at index 2 [OK]
Hint: Check middle element first to find target quickly [OK]
Common Mistakes:
  • Confusing index with value
  • Not updating low or high correctly
  • Assuming target not found returns 0
4. Identify the error in the following iterative binary search code snippet and choose the correct fix:
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;
}
medium
A. Change while condition to 'while (low <= high)'
B. Change mid calculation to '(low + high) / 2'
C. Remove 'return -1;' at the end
D. Change 'low = mid + 1;' to 'low = mid - 1;'

Solution

  1. Step 1: Analyze loop condition

    The loop uses 'while (low < high)', which misses checking when low equals high, possibly skipping the last element.
  2. Step 2: Correct loop condition

    Changing to 'while (low <= high)' ensures all elements are checked including when low equals high.
  3. Final Answer:

    Change while condition to 'while (low <= high)' -> Option A
  4. Quick Check:

    Loop must include low == high to check all elements [OK]
Hint: Use <= in loop to include last element check [OK]
Common Mistakes:
  • Using < instead of <= in loop condition
  • Incorrect mid calculation causing overflow
  • Wrong update of low or high pointers
5. Given a sorted array with possible duplicate elements, how can you modify the iterative binary search to find the first occurrence of a target value?
hard
A. Return immediately when target is found
B. When target is found, continue searching left half to find earlier occurrence
C. Search only the right half after finding target
D. Use linear search instead of binary search

Solution

  1. Step 1: Understand duplicates in sorted array

    Duplicates mean target can appear multiple times; we want the first index where it appears.
  2. 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.
  3. Final Answer:

    When target is found, continue searching left half to find earlier occurrence -> Option B
  4. Quick Check:

    Find first occurrence by searching left after match [OK]
Hint: On match, move left to find first occurrence [OK]
Common Mistakes:
  • Stopping search immediately on first match
  • Searching right half after finding target
  • Switching to linear search unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard