Topics/Binary Search/Lower/upper bound

Pattern

Lower/upper bound

Lower/upper bound is a reusable approach under Binary Search. Once you recognize the shape of the input and the ask, this pattern gives you a standard plan instead of inventing a new algorithm from scratch.

Binary SearchPatternsPattern

When to use it

Reach for Lower/upper bound when a binary search problem matches the cues in this lesson — especially after you’ve ruled out a brute-force nested scan.

How it works

  1. Restate the Binary Search problem in one sentence and name the constraint that Lower/upper bound exploits.
  2. Sketch the invariant Lower/upper bound maintains (what stays true after each step).
  3. Walk a tiny example by hand, writing the state after every update.
  4. Translate that walk into code in your interview language, then list edge cases.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionLower/upper bound

Why interviewers care

Interviewers grade pattern recognition. Naming Lower/upper bound early shows you can classify the problem inside Patterns.

Drill Lower/upper bound with Binary Search problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Overflow mid = (lo+hi)/2
  • !Wrong inclusive/exclusive bounds
  • !Infinite loop when mid doesn't move
Loading visualization…

Practice this

Related Binary Search problems — open any one and apply Lower/upper bound.

Search bank →

More under Binary Search

← Back to Binary Search lesson