Skip to content
Learn Netverks

Lesson

Step 17/36 47% through track

binary-search

Binary search

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Binary search: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

These patterns turn O(n²) scans into O(n log n) or O(n)—core interview toolkit.

You will apply Binary search in contexts like: Interview loops, performance tuning, and foundational CS courses.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on. Also trace indices on paper for a small example input.

When you can explain the previous lesson's ideas in your own words.

Binary search halves the search space on sorted data—O(log n) time, O(1) space. Also applies to "answer space" monotonic problems (min capacity, max speed).

Template

  • Maintain lo, hi inclusive or half-open—pick one style and stay consistent
  • Mid avoids overflow: lo + (hi - lo) / 2
  • Compare mid with target; discard half

std::lower_bound

STL lower_bound returns first position not less than value—O(log n) on sorted ranges.

Manual search

#include 
#include 
#include 

int main() {
    std::vector a = {3, 5, 7, 9, 11};
    int target = 7;
    auto it = std::lower_bound(a.begin(), a.end(), target);
    if (it != a.end() && *it == target)
        std::cout << "found at " << (it - a.begin()) << "\n";
    return 0;
}

Important interview questions and answers

  1. Q: Binary search on answer?
    A: When feasibility is monotonic in parameter—search parameter space.
  2. Q: Unsorted array?
    A: Sort first O(n log n) or use hash map for exact lookup O(n) average.

Self-check

  1. Why must data be sorted for classic binary search?
  2. What does lower_bound return?

Tip: Use lo + (hi - lo) / 2 to avoid overflow and impress interviewers.

Interview prep

Requirement?

Sorted order or monotonic predicate on answer space.

lower_bound?

First element not less than target—O(log n).

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Precondition?
  • lower_bound idea?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump