DEV Community

M.T.Ramkrushna
M.T.Ramkrushna

Posted on

DSA: Topic 5: Binary Search

Interview frequency: ⭐⭐⭐⭐⭐

Most beginners think Binary Search is just:

"Find an element in a sorted array."

In reality, that's only 10% of its interview usage.

Most interview questions use Binary Search on the Answer.


What Interviewers Want

When interviewers ask a Binary Search question, they're testing whether you can recognise:

  • A sorted search space.
  • A monotonic condition (once something becomes true, it stays true—or vice versa).
  • How to reduce a search from O(n) to O(log n).

Part 1: Classic Binary Search

Suppose you have:

nums = [2, 5, 8, 10, 15, 20, 30]
target = 15
Enter fullscreen mode Exit fullscreen mode

Instead of checking each element:

2 → 5 → 8 → 10 → 15
Enter fullscreen mode Exit fullscreen mode

Binary Search repeatedly cuts the search space in half.

2 5 8 10 15 20 30
      ↑
     mid
Enter fullscreen mode Exit fullscreen mode

If:

nums[mid] == target
Enter fullscreen mode Exit fullscreen mode

You're done.

If:

nums[mid] < target
Enter fullscreen mode Exit fullscreen mode

Discard the left half.

If:

nums[mid] > target
Enter fullscreen mode Exit fullscreen mode

Discard the right half.


Code

def binary_search(nums, target):
    left = 0
    right = len(nums) - 1

    while left <= right:

        mid = left + (right - left) // 2

        if nums[mid] == target:
            return mid

        elif nums[mid] < target:
            left = mid + 1

        else:
            right = mid - 1

    return -1
Enter fullscreen mode Exit fullscreen mode

Complexity:

Time : O(log n)

Space: O(1)
Enter fullscreen mode Exit fullscreen mode

Why is it O(log n)?

Imagine:

1,000,000 elements
Enter fullscreen mode Exit fullscreen mode

Linear Search

Worst case

1,000,000 comparisons
Enter fullscreen mode Exit fullscreen mode

Binary Search

1,000,000

↓

500,000

↓

250,000

↓

125,000

↓

...
Enter fullscreen mode Exit fullscreen mode

Only about 20 comparisons.

That's why it's so powerful.


Interview Trick #1

The array must be sorted.

If it isn't:

Don't immediately think Binary Search.


Part 2: First and Last Occurrence

Example

[1,2,2,2,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Find the first occurrence of 2.

Normal Binary Search might return:

index = 3
Enter fullscreen mode Exit fullscreen mode

Wrong.

Expected:

index = 1
Enter fullscreen mode Exit fullscreen mode

Interview trick:

When you find the target,

don't stop.

Continue searching the left half.

Similarly,

for the last occurrence,

continue searching the right half.


Part 3: Lower Bound & Upper Bound

Many companies ask this.

Example

nums = [2,4,4,4,8]
Enter fullscreen mode Exit fullscreen mode

Lower Bound of 4

First position ≥ 4
Enter fullscreen mode Exit fullscreen mode

Answer

1
Enter fullscreen mode Exit fullscreen mode

Upper Bound

First position > 4
Enter fullscreen mode Exit fullscreen mode

Answer

4
Enter fullscreen mode Exit fullscreen mode

Part 4: Binary Search on the Answer ⭐⭐⭐⭐⭐

This is where interviews become interesting.

Suppose the interviewer asks:

Koko eats bananas.

Find the minimum eating speed.

The array is not sorted.

Can we still use Binary Search?

Yes.

Because the answer space is sorted.


Possible speeds:

1

2

3

4

5

6

7

...
Enter fullscreen mode Exit fullscreen mode

Suppose:

Speed = 3

Impossible
Enter fullscreen mode Exit fullscreen mode
Speed = 4

Possible
Enter fullscreen mode Exit fullscreen mode
Speed = 5

Possible
Enter fullscreen mode Exit fullscreen mode
Speed = 6

Possible
Enter fullscreen mode Exit fullscreen mode

Notice the pattern.

False False False True True True
Enter fullscreen mode Exit fullscreen mode

This is called a monotonic condition.

Binary Search works because once it becomes True, it stays True.


How to Recognise Binary Search on the Answer

Ask yourself:

Am I searching for the minimum or maximum value that satisfies a condition?

Examples:

  • Minimum speed
  • Minimum capacity
  • Maximum distance
  • Smallest feasible answer

These are strong hints.


Generic Template

left = minimum_possible_answer
right = maximum_possible_answer

while left < right:

    mid = (left + right) // 2

    if is_possible(mid):
        right = mid
    else:
        left = mid + 1

return left
Enter fullscreen mode Exit fullscreen mode

This template appears in many interview problems.


Common Interview Mistakes

Mistake 1

Using:

mid = (left + right) // 2
Enter fullscreen mode Exit fullscreen mode

This is fine in Python because integers don't overflow, but in languages like Java or C++, interviewers often expect:

mid = left + (right - left) // 2
Enter fullscreen mode Exit fullscreen mode

It's a good habit across languages.


Mistake 2

Wrong loop condition

Many candidates write:

while left < right
Enter fullscreen mode Exit fullscreen mode

when they should use

while left <= right
Enter fullscreen mode Exit fullscreen mode

Know which variant you're implementing.


Mistake 3

Updating the wrong pointer.

Remember:

Target is larger

↓

Move left
Enter fullscreen mode Exit fullscreen mode
Target is smaller

↓

Move right
Enter fullscreen mode Exit fullscreen mode

Real Interview Questions

Easy

  1. Binary Search ⭐⭐⭐⭐⭐

  2. Search Insert Position ⭐⭐⭐⭐


Medium

  1. First & Last Position ⭐⭐⭐⭐⭐

  2. Search in Rotated Sorted Array ⭐⭐⭐⭐⭐

  3. Find Minimum in Rotated Sorted Array ⭐⭐⭐⭐

  4. Peak Element ⭐⭐⭐⭐


Binary Search on Answer

  1. Koko Eating Bananas ⭐⭐⭐⭐⭐

  2. Capacity to Ship Packages Within D Days ⭐⭐⭐⭐⭐

  3. Split Array Largest Sum ⭐⭐⭐⭐⭐

  4. Aggressive Cows (very popular in competitive programming and some interviews) ⭐⭐⭐⭐


Interview Checklist

When you read a question, ask:

  1. Is the data already sorted?
  • If yes → Consider classic Binary Search.
  1. Am I searching for a minimum or maximum feasible value?
  • If yes → Think Binary Search on the Answer.
  1. Does the condition change only once?
  • Example:

     False False False True True True
    

    or

     True True True False False
    
  • If yes → Binary Search is likely applicable.


Summary of Topics Covered

Topic Interview Frequency Key Idea
Arrays ⭐⭐⭐⭐⭐ Traversal and manipulation
Hash Maps & Sets ⭐⭐⭐⭐⭐ Fast lookups and counting
Two Pointers ⭐⭐⭐⭐⭐ Efficient pair and in-place problems
Sliding Window ⭐⭐⭐⭐⭐ Contiguous subarrays/substrings
Binary Search ⭐⭐⭐⭐⭐ Search efficiently in sorted or monotonic spaces

These five topics form the foundation of a large portion of coding interview problems. The next topic is Stacks & Monotonic Stacks, another extremely common interview pattern used for problems like Valid Parentheses, Daily Temperatures, Next Greater Element, and Largest Rectangle in a Histogram.

Top comments (0)