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 on the Answer

Technique · CP 2400+

Aliens Trick (Lagrangian relaxation / WQS binary search)

When f(k), the best answer using exactly k groups, is convex in k: drop the k constraint and charge lambda per group. Solve the easier DP with no k dimension, then binary search lambda until the optimum uses k groups. The answer is g(lambda) + lambda*k.

Learn firstBinary Search on the Answer1D / Fibonacci-styleState Machine DP (Stocks)
0%
mastery
0/2 solved
Practise nextNew Year and Handle Change
IdeaPracticePitfalls

Recognise it

The signal

exactly k segments/operations/transactions with large n and k

  1. 1Brute force

    dp[i][j] for j up to k: O(nk) or worse.

  2. 2The observation

    The k dimension of the DP.

  3. 3Why it works

    For penalty lambda, the optimal group count is monotone in lambda. Ties must be broken consistently (always the min count, or always the max).

Reach for it when

  • +the version with any number of groups is an O(n) or O(n log n) DP
  • +the marginal gain of each extra group never increases

Not when

  • ×f(k) is not convex (check by brute force on small cases)
  • ×k is small enough for the 2D DP

Practice

Next

New Year and Handle Change

0/2 solved
  • New Year and Handle ChangeCodeforces2800
  • Gosha is huntingCodeforces3000

Pitfalls

Misconceptions

  • !without consistent tie-breaking the search skips over k
  • !using a real-valued lambda when an integer lambda suffices for integer costs
Go deeperresources

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