Lesson 2 of 66 5 min

Problem: Binary Search (Easy)

Master the quintessential search algorithm. Learn how to eliminate half the search space in every step to achieve logarithmic time complexity.

1. Problem Statement

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with $O(\log n)$ runtime complexity.

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4

Imagine you are looking for the word "Masterclass" in a printed dictionary. You don't start at page 1. You open the dictionary in the middle.

  • If the word you find is "Pizza," you know "Masterclass" must be in the first half.
  • You throw away the entire second half of the book and repeat the process.

This is the power of Monotonicity. Because the array is sorted, every comparison allows you to discard 50% of the remaining work.

3. Visual Execution (Divide & Conquer)

graph TD
    Start[Target: 9] --> Range[Search Range: 0 to 5]
    Range --> Mid[Mid: index 2 val: 3]
    Mid -- 3 < 9 --> NewRange[Search Range: 3 to 5]
    NewRange --> NewMid[Mid: index 4 val: 9]
    NewMid -- 9 == 9 --> Found[Return index 4]

4. Java Implementation (Optimal)

public int search(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;

    while (left <= right) {
        // Optimization: Prevent integer overflow
        int mid = left + (right - left) / 2;

        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid + 1; // Discard left half
        } else {
            right = mid - 1; // Discard right half
        }
    }

    return -1;
}

5. Verbal Interview Script (Staff Tier)

Interviewer: "Why is binary search O(log N)?"

You: "Binary search is logarithmic because at each iteration, the search space is divided by exactly two. If we have $N$ elements, after the first step we have $N/2$, then $N/4$, and so on. Mathematically, the number of steps required to reduce the search space to 1 is the power to which we must raise 2 to get $N$, which is $\log_2(N)$. In a senior role, I also prioritize the Overflow Check: instead of (left + right) / 2, I use left + (right - left) / 2 to ensure that for massive arrays near $2^{31}-1$, my pointer doesn't wrap around and cause a crash."

6. Staff-Level Follow-Ups

Follow-up 1: "Can we use recursion?"

  • The Answer: "Yes, but in Java, iterative binary search is generally preferred. Recursion adds $O(\log N)$ overhead to the call stack, whereas the iterative version uses $O(1)$ space. For systems where stack space is constrained, iteration is the safer engineering choice."

Follow-up 2: "What if the target is NOT in the array? Where would it be inserted?"

  • The Answer: "This is the 'Search Insert Position' variation. If the loop terminates without finding the target, the left pointer will always point to the index where the target should have been to maintain sorted order."

7. Performance Nuances (The Java Perspective)

  1. Arrays.binarySearch(): In production, I would often use the built-in java.util.Arrays.binarySearch(nums, target). It uses this exact logic but returns (-(insertion point) - 1) if the element is not found, providing more information than a simple -1.
  2. Branch Prediction: Binary search is very fast, but for extremely small arrays (e.g., size < 16), a simple linear scan can sometimes be faster because it is easier for the CPU to perform Branch Prediction on a linear loop than on the jumpy logic of binary search.

6. Staff-Level Verbal Masterclass (Communication)

Interviewer: "How would you defend this specific implementation in a production review?"

You: "In a mission-critical environment, I prioritize the Big-O efficiency of the primary data path, but I also focus on the Predictability of the system. In this implementation, I chose a recursive approach with memoization. While a recursive solution is more readable, I would strictly monitor the stack depth. If this were to handle skewed inputs, I would immediately transition to an explicit stack on the heap to avoid a StackOverflowError. From a memory perspective, I leverage primitive arrays to ensure that we minimize the garbage collection pauses (Stop-the-world) that typically plague high-throughput Java applications."

7. Global Scale & Distributed Pivot

When a problem like this is moved from a single machine to a global distributed architecture, the constraints change fundamentally.

  1. Data Partitioning: We would shard the input space using Consistent Hashing. This ensures that even if our dataset grows to petabytes, any single query only hits a small subset of our cluster, maintaining logarithmic lookup times.
  2. State Consistency: For problems involving state updates (like DP or Caching), we would use a Distributed Consensus protocol like Raft or Paxos to ensure that all replicas agree on the final state, even in the event of a network partition (The P in CAP theorem).

8. Performance Nuances (The Staff Perspective)

  1. Cache Locality: Accessing a 2D matrix in row-major order (reading [i][j] then [i][j+1]) is significantly faster than column-major order in modern CPUs due to L1/L2 cache pre-fetching. I always structure my loops to align with how the memory is physically laid out.
  2. Autoboxing and Generics: In Java, using List<Integer> instead of int[] can be 3x slower due to the overhead of object headers and constant wrapping. For the most performance-sensitive sections of this algorithm, I advocate for primitive specialized structures.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.