Bird
Raised Fist0
DSA Goprogramming~20 mins

Binary Search Iterative Approach in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Binary Search Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Binary Search for Existing Element
What is the output of the following Go code that performs an iterative binary search for the number 7 in a sorted array?
DSA Go
package main
import "fmt"

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
}

func main() {
    arr := []int{1, 3, 5, 7, 9, 11}
    fmt.Println(binarySearch(arr, 7))
}
A-1
B2
C3
D4
Attempts:
2 left
💡 Hint
Remember that array indices start at 0 and the array is sorted.
❓ Predict Output
intermediate
2:00remaining
Output of Binary Search for Non-Existing Element
What is the output of the following Go code that performs an iterative binary search for the number 7 in a sorted array?
DSA Go
package main
import "fmt"

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
}

func main() {
    arr := []int{2, 4, 6, 8, 10, 12}
    fmt.Println(binarySearch(arr, 7))
}
A4
B3
C2
D-1
Attempts:
2 left
💡 Hint
Check if the target exists in the array and note its index.
❓ Predict Output
advanced
2:00remaining
Output of Binary Search with Duplicate Elements
What is the output of the following Go code that performs an iterative binary search for the number 5 in a sorted array with duplicates?
DSA Go
package main
import "fmt"

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
}

func main() {
    arr := []int{1, 3, 5, 5, 5, 7, 9}
    fmt.Println(binarySearch(arr, 5))
}
A2
B3
C4
D-1
Attempts:
2 left
💡 Hint
Binary search may return any index where the target is found.
🧠 Conceptual
advanced
1:30remaining
Why Use Iterative Binary Search Instead of Recursive?
Which of the following is the main advantage of using an iterative approach for binary search over a recursive one?
AIterative approach uses less memory by avoiding function call stack overhead.
BIterative approach is easier to write and understand than recursive.
CIterative approach can handle unsorted arrays.
DIterative approach always finds the first occurrence of duplicates.
Attempts:
2 left
💡 Hint
Think about memory usage and function calls.
🔧 Debug
expert
2:30remaining
Identify the Bug in Binary Search Implementation
What error will the following Go code produce when running binary search on the array [1, 2, 3, 4, 5] searching for 6?
DSA Go
package main
import "fmt"

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
}

func main() {
    arr := []int{1, 2, 3, 4, 5}
    fmt.Println(binarySearch(arr, 6))
}
Aruntime error: index out of range
Breturns 2 (correct index)
Creturns -1 (not found)
Dcompilation error
Attempts:
2 left
💡 Hint
Check the initial value of 'high' and array indexing.

Practice

(1/5)
1. What is the main purpose of the mid variable in the iterative binary search algorithm?
easy
A. To keep track of the number of iterations
B. To store the target value to search
C. To find the middle index of the current search range
D. To hold the entire array being searched

Solution

  1. Step 1: Understand the role and importance of mid in binary search

    The mid variable calculates the middle index between the current low and high indices to split the search range. By checking the element at mid, the algorithm decides whether to search the left or right half next, making the search efficient.
  2. Final Answer:

    To find the middle index of the current search range -> Option C
  3. Quick Check:

    mid = middle index [OK]
Hint: Mid splits search range in half each step [OK]
Common Mistakes:
  • Confusing mid with target value
  • Using mid as a counter instead of index
  • Not updating mid inside the loop
2. Which of the following is the correct way to calculate the middle index mid in Go to avoid integer overflow?
easy
A. mid := (low + high) / 2
B. mid := (high - low) / 2
C. mid := (low - high) / 2
D. mid := low + (high - low) / 2

Solution

  1. Step 1: Understand integer overflow risk and safe calculation

    Adding low + high directly can overflow if both are large integers. Calculating mid as low + (high - low) / 2 avoids overflow by subtracting first.
  2. Final Answer:

    mid := low + (high - low) / 2 -> Option D
  3. Quick Check:

    Safe mid calculation avoids overflow [OK]
Hint: Use low + (high - low)/2 to prevent overflow [OK]
Common Mistakes:
  • Using (low + high)/2 directly causing overflow
  • Subtracting incorrectly causing negative mid
  • Confusing order of operations
3. What will be the output of the following Go code snippet?
package main
import "fmt"

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
}

func main() {
    arr := []int{2, 4, 6, 8, 10}
    result := binarySearch(arr, 6)
    fmt.Println(result)
}
medium
A. 3
B. 2
C. -1
D. 0

Solution

  1. Step 1: Trace the binary search for target 6 and verify return

    Array is [2,4,6,8,10]. Initial low=0, high=4. mid=2. arr[2]=6 matches target. Function returns mid = 2 immediately.
  2. Final Answer:

    2 -> Option B
  3. Quick Check:

    Index of 6 in array = 2 [OK]
Hint: Check mid index value equals target first [OK]
Common Mistakes:
  • Returning value instead of index
  • Off-by-one errors in mid calculation
  • Not updating low/high correctly
4. Identify the bug in this iterative binary search code snippet in Go:
func binarySearch(arr []int, target int) int {
    low, high := 0, len(arr)
    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
}
medium
A. The initial value of high should be len(arr) - 1
B. The loop condition should be low < high
C. The mid calculation causes overflow
D. The function should return arr[mid] instead of mid

Solution

  1. Step 1: Check high initialization and correct it

    High is set to len(arr), which is out of array index range (max index is len(arr)-1). Set high to len(arr) - 1 to avoid index out of range error when accessing arr[mid].
  2. Final Answer:

    The initial value of high should be len(arr) - 1 -> Option A
  3. Quick Check:

    High = len(arr)-1 fixes index error [OK]
Hint: High index must be last valid array index [OK]
Common Mistakes:
  • Setting high to len(arr) causing runtime error
  • Using wrong loop condition
  • Returning value instead of index
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. When arr[mid] == target, update high = mid - 1 and continue searching
B. Return mid immediately when arr[mid] == target
C. When arr[mid] == target, update low = mid + 1 and continue searching
D. Use linear search after binary search to find first occurrence

Solution

  1. Step 1: Understand duplicates issue and modify search logic

    Standard binary search returns any occurrence, not necessarily the first. When arr[mid] == target, move high to mid - 1 to continue searching left side for earlier occurrence, but store mid as potential answer.
  2. Final Answer:

    When arr[mid] == target, update high = mid - 1 and continue searching -> Option A
  3. Quick Check:

    Adjust high to find first occurrence [OK]
Hint: Move high left on match to find first occurrence [OK]
Common Mistakes:
  • Returning immediately on first match
  • Moving low right on match losing first occurrence
  • Using 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