00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each comparison throws away half of the remaining range, so at most about log2 n + 1 comparisons are needed: 20 comparisons are enough for a million elements.

Approaches

Both approaches halve the range in the same way. One uses a loop; the other recurses.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the array. The range halves at every step, so both versions make O(log n) comparisons.

Interview Tips and Recommended Approach

  • The array must be sorted. Binary search on unsorted data gives wrong answers silently.
  • Use the overflow-safe midpoint. (lo + hi) / 2 overflowed in the JDK itself for years.
  • Get the loop condition right. lo ≤ hi with mid ± 1 avoids infinite loops.
  • Know Arrays.binarySearch(). It returns -(insertion point) - 1 for a missing key, not just -1.

Recommended Approach: Iterative

Why: it runs in logarithmic time with constant memory and is the template for many variants, such as first or last occurrence and search in rotated arrays.