Binary Search · 12 min · free lesson

Exact Binary Search: When to Use It

Recognise the problem shape before choosing Exact Binary Search.

Core idea

The insertion position may contain a larger value or lie at the end. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Discard the half that cannot contain the target after comparing the midpoint.

O(log n) time · O(1) space19 execution steps
main · before line 19Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example input[-1,0,3,5,9,12]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 19
fn exact_index(values: &[i32], target: i32) -> i32 {
    let (mut lo, mut hi) = (0, values.len());
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        if values[mid] < target {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    if values.get(lo) == Some(&target) {
        lo as i32
    } else {
        -1
    }
}
 
fn main() {
    let result = exact_index(&[-1, 0, 3, 5, 9, 12], 9).to_string();
    println!("{result}");
}

Try your own version

Compare the visible input `[-1,0,3,5,9,12]` with `[0,2,6,10]`. Predict why their results are `4` and `-1`. Then change one legal value and explain whether the same invariant, the insertion position may contain a larger value or lie at the end, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Binary Search infographic; panel 1 illustrates Binary Exact.
Binary Exact: follow panel 1 to see the operation, then trace this lesson's example.

Understand it

For [-1,0,3,5,9,12], lower-bound elimination leaves index 4. Its value equals 9, so return 4. If the insertion point has another value, return -1 rather than treating the insertion position as a match.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Return the index of 9, or -1 if absent. The visible fixture is [-1,0,3,5,9,12] and its example result is 4. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Exact Binary Search when it asks for exact lookup in sorted random-access data. Here the concrete task is: Return the index of 9, or -1 if absent. The visible input [-1,0,3,5,9,12] is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. It needs ordering, a monotone predicate, or another proved structure that lets one half be discarded; merely containing numbers is not enough. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Discard the half that cannot contain the target after comparing the midpoint. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? Binary search maintains an interval that is still capable of containing the answer. State precisely why the discarded half cannot contain it. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is O(log n) time · O(1) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 4 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Check no match, duplicate matches, the first and last valid positions, and an answer at the boundary of the search domain. Use half-open bounds consistently and compute the midpoint without overflowing large integer indices. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Discard the half that cannot contain the target after comparing the midpoint.

When to use it: exact lookup in sorted random-access data

Complexity: O(log n) time · O(1) space

Input: [-1,0,3,5,9,12]

Read the code

fn exact_index(values: &[i32], target: i32) -> i32 {
    let (mut lo, mut hi) = (0, values.len());
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        if values[mid] < target {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    if values.get(lo) == Some(&target) {
        lo as i32
    } else {
        -1
    }
}

fn main() {
    let result = exact_index(&[-1, 0, 3, 5, 9, 12], 9).to_string();
    println!("{result}");
}

Complete std-only binary-exact program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Exact Binary Search on input [1,4,4,8,9]. Which result follows from the documented contract?

Reveal the answer
  1. 5
  2. 4
  3. 3

For this input the result is 4. The insertion position may contain a larger value or lie at the end. Compare this independent fixture with the worked trace: For [-1,0,3,5,9,12], lower-bound elimination leaves index 4. Its value equals 9, so return 4. If the insertion point has another value, return -1 rather than treating the insertion position as a match.

Go deeper

Common misconception: “Every lower bound is an exact match”

The insertion position may contain a larger value or lie at the end. For [-1,0,3,5,9,12], lower-bound elimination leaves index 4. Its value equals 9, so return 4. If the insertion point has another value, return -1 rather than treating the insertion position as a match.

  1. Concrete transition: For [-1,0,3,5,9,12], lower-bound elimination leaves index 4. Its value equals 9, so return 4. If the insertion point has another value, return -1 rather than treating the insertion position as a match.
  2. Independent second fixture: Input [1,4,4,8,9] produces 4. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input [4,8,8,8,12] produces -1. The insertion position may contain a larger value or lie at the end. The stated work bound is O(log n) time · O(1) space. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input [-1,0,3,5,9,12] with [0,2,6,10]. Predict why their results are 4 and -1. Then change one legal value and explain whether the same invariant, the insertion position may contain a larger value or lie at the end, still applies.

Connections

  • Exact Binary Search: Mental Model: Discard the half that cannot contain the target after comparing the midpoint.
  • Challenge: Exact Binary Search: Return the index of 9, or -1 if absent.
Reveal the Algorithm Atlas answer

4

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Exact Binary Search: When to Use It (courseId "algorithms", lessonId "algorithm.binary-exact.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.binary-exact.recognize
Goal: The insertion position may contain a larger value or lie at the end. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.binary-exact.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.