Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Binary Search/Binary Search

Technique · CP 1600

Interactive Problems (query-limited search)

The input is hidden behind a query API with a budget. Design the queries (usually binary or ternary splits, sometimes comparison sorting) so the worst case fits the budget, and flush after each query.

Learn firstBinary Search
0%
mastery
0/10 solved
Practise nextGuess Number Higher or Lower
IdeaPracticePitfalls

Recognise it

The signal

'you may ask at most q queries'

  1. 1Brute force

    Query every element: over the budget.

  2. 2The observation

    The number of queries, not running time.

  3. 3Why it works

    After each answer the candidate set is consistent with every answer so far and has shrunk by a constant factor.

Reach for it when

  • +an API such as guess(x), compare(i, j), MountainArray.get(i)
  • +budget about log2(n) or n log n

Not when

  • ×adaptive judges that move the answer (count worst-case information, not average)

Practice

Next

Guess Number Higher or Lower

0/10 solved
  • Guess Number Higher or LowerGoogle, Morgan StanleyEasy
  • InterviewCodeforces1300
  • Find the CelebrityPremiumMedium
  • Hidden IntegerCSESMedium
  • Hidden PermutationCSESMedium
  • Guess the K-th Zero (Easy version)Codeforces1600
  • Bear and Prime 100Codeforces1400
  • Find in Mountain ArrayHard
  • K-th Highest ScoreCSESHard
  • Colored ChairsCSESHard

Pitfalls

Misconceptions

  • !forgetting to flush output (CF/CSES)
  • !repeated queries count against the limit unless memoised
Go deeper1 combinations · resources

Combinations

  • Interactive Problems (query-limited search)+Prefix Sum

    find the single altered element using range-sum queries within log n queries

    Interactive Problems (query-limited search):
    query a range sum and compare to binary search for the heavier element
    Prefix Sum:
    know the expected sum of any range

    Interview

Resources

  • Binary searchcp-algorithms · article
  • Binary SearchUSACO Guide · course
  • ITMO Binary Search courseCodeforces EDU · course
  • Binary Search explore cardLeetCode · course
  • Sorting and searching cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems