Guess Number Higher or Lower II solution explained

Guess Number Higher or Lower II asks for the least money that guarantees you find a secret number from 1 to n, when every wrong guess g costs g and tells you whether the secret is higher or lower. Treat it as a game against an adversary who always sends you to the more expensive side. For a range lo to hi, cost(lo, hi) is the minimum over guesses g of g + max(cost(lo, g - 1), cost(g + 1, hi)), and a range of one or zero numbers costs nothing. Filling that table by range length takes O(n³) time and O(n²) memory.

By Published 8 min read

The problem, restated

Someone picks a whole number from 1 to n. You guess. If you are right, the game ends. If you are wrong, you pay an amount equal to your guess and learn whether the secret is higher or lower, then guess again. You must say how much money you need at the start so that, with the best plan, you can always finish without running out, whatever number was picked.

Values printed by the code below
nMoney neededBest first guesses
101 (nothing to pay)
211
322
441 or 3
562 or 4
8125
10167
Values printed by the code below. Scroll sideways on a small screen.

For n = 4, guessing 3 first works like this: if wrong you pay 3. If the secret is lower, you guess 1 among {1, 2}; if wrong you pay 1 more and know it is 2. If it is higher, it must be 4. The worst case totals 4.

What the interviewer is checking

The classic trap is to assume binary search is best because it minimizes the number of guesses. Here the cost of a guess is its value, so minimizing count is the wrong goal. Interviewers want you to say "worst case" clearly, express it as min over my choice of max over the adversary's response, and then recognize an interval DP. Getting the loop order right for a range table is the second thing they check.

Clarify first

  • Do I pay for the correct guess? No, only wrong guesses cost money.
  • Is the answer an expected cost or a worst case? Worst case: the money must suffice for any secret.
  • Can the secret change during the game? It does not need to; thinking of it as an adversary is just a way to compute the worst case.

Brute force: every guessing strategy

Without a cache, the recursion below tries every first guess, then every next guess on each side, and so on. The same small ranges, such as 3 to 5, come up again under many different earlier guesses, so the work grows exponentially. For n up to about 10 it still finishes quickly, which makes it a good oracle: this page's table was checked against it for n = 1 to 10 before being trusted for larger n.

Why binary search is not the answer

If you always guess the middle of the range, the costs for n = 1 to 12 come out as 0, 1, 2, 5, 7, 8, 10, 17, 20, 22, 25, 26, while the true minimums are 0, 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 21. Middle guesses are cheap on the left half but leave the expensive right half to be searched with high-value guesses. For every n from 8 to 40 the best first guess is to the right of the middle (for n = 10 it is 7), so the costly upper side is the shorter one.

The minimax recurrence

Suppose the secret is somewhere in lo to hi. If you guess g and are wrong, you pay g and continue in either lo to g - 1 or g + 1 to hi. You do not control which, so plan for the worse of the two. The cost of guessing g is g + max(cost(lo, g - 1), cost(g + 1, hi)). You control g, so take the minimum over all g in the range. A range with one number costs 0 because you guess it and are right; an empty range also costs 0.

from functools import lru_cache

def money_needed(n):
    @lru_cache(maxsize=None)
    def cost(lo, hi):
        if lo >= hi:
            return 0
        return min(g + max(cost(lo, g - 1), cost(g + 1, hi)) for g in range(lo, hi + 1))

    return cost(1, n)
Python: memoized recursion. O(n^2) ranges, O(n) guesses each.

Bottom-up by range length

A range depends only on shorter ranges inside it, so fill the table by length: all ranges of length 2, then length 3, and so on up to the full range. Size the table n + 2 so that g + 1 can reach n + 1 without going out of bounds.

function getMoneyAmount(n) {
  const cost = Array.from({ length: n + 2 }, () => new Array(n + 2).fill(0));
  for (let len = 2; len <= n; len++) {
    for (let lo = 1; lo + len - 1 <= n; lo++) {
      const hi = lo + len - 1;
      let best = Infinity;
      for (let g = lo; g <= hi; g++) {
        const worst = g + Math.max(cost[lo][g - 1], cost[g + 1][hi]);
        if (worst < best) best = worst;
      }
      cost[lo][hi] = best;
    }
  }
  return cost[1][n];
}
JavaScript: interval table filled by length.

When g equals lo, cost[lo][lo - 1] is read. That cell is never written and stays 0, which is right for an empty range. The same holds for cost[hi + 1][hi] when g equals hi.

Recovering the plan

Interviewers sometimes ask what you would actually guess. Store the best g for each range while filling the table, then walk it: guess plan[lo][hi], and move to the side the answer points to. Playing this plan against every possible secret is also the best way to test the table, because the worst total you pay must equal the computed cost.

def guessing_plan(n):
    cost = [[0] * (n + 2) for _ in range(n + 2)]
    plan = [[0] * (n + 2) for _ in range(n + 2)]
    for length in range(2, n + 1):
        for lo in range(1, n - length + 2):
            hi = lo + length - 1
            cost[lo][hi] = float("inf")
            for g in range(lo, hi + 1):
                worst = g + max(cost[lo][g - 1], cost[g + 1][hi])
                if worst < cost[lo][hi]:
                    cost[lo][hi], plan[lo][hi] = worst, g
    return cost[1][n] if n >= 1 else 0, plan


def amount_paid(n, plan, secret):
    lo, hi, paid = 1, n, 0
    while lo < hi:
        g = plan[lo][hi]
        if g == secret:
            return paid
        paid += g
        if secret < g:
            hi = g - 1
        else:
            lo = g + 1
    return paid
Python: table with the chosen guess, plus a player that follows it.

Complexity

Numbers 1 to n
ApproachTimeExtra memory
Recursion without a cacheExponentialO(n) stack
Memoized recursionO(n³)O(n²)
Table by range lengthO(n³)O(n²)
Numbers 1 to n. Scroll sideways on a small screen.

The cubic table is the answer interviewers expect. If asked to speed it up, a reasonable first step is to measure which guesses ever win for each range before trying to prove a narrower search; do not claim a pruning rule you have not checked.

Edge cases

  • n = 1: no money needed.
  • n = 2: guess 1; worst case you pay 1 and know the answer.
  • Ranges where g is at either end, which read an empty range on one side.
  • Large n, where recursion depth and the n² table both matter; the bottom-up table avoids deep recursion.

Common mistakes

  • Answering with the cost of binary search, which first overpays at n = 4 and does so for every n from 8 to 12 in the lists above.
  • Summing the two sides instead of taking the max: only one side is ever played.
  • Taking the min over the two sides, which models a lucky secret instead of a worst case.
  • Charging for the correct guess, which adds the secret to every path.
  • Filling the table by lo from 1 upward, so cost[g + 1][hi] is read before it is computed.

How to explain it out loud

Fictional example

Saying min and max in the right places
Candidate
The budget has to cover the worst case, so I think of the secret as an adversary. For a range, I choose a guess, and the adversary chooses which side I continue on.
Candidate
So the cost of a guess g is g plus the larger of the two side costs, and the cost of the range is the minimum of that over all guesses. Ranges of size one or zero cost nothing.
Interviewer
Why not binary search?
Candidate
Binary search minimizes how many guesses, but here guesses cost their value. For n equal to 4, guessing 2 first needs 5, while guessing 3 first needs 4.

Minimum Cost Tree From Leaf Values is another interval DP that tries every split point of a range. Palindrome Partitioning II chooses cut positions too, but over a prefix rather than an interval. Predict the Winner and Stone Game II are the other minimax problems here, and Sqrt(x) is a reminder of where plain binary search is the right tool.

Practicing with Natively

The binary search trap is the moment this problem is decided, so practice catching it out loud. Run a mock round on Mac or Windows with Natively transcribing and look back at whether you said "worst case" before reaching for binary search. Once you have your own answer, Natively can read the problem from a screenshot and suggest an approach to compare. More on the AI interview assistant.

Questions people ask

How do you solve Guess Number Higher or Lower II?

Use an interval DP: cost(lo, hi) is 0 when lo >= hi, and otherwise the minimum over guesses g of g + max(cost(lo, g - 1), cost(g + 1, hi)). The answer is cost(1, n).

Why isn't binary search the answer?

Binary search minimizes the number of guesses, but here each wrong guess costs its value. For n = 4, guessing 2 first needs 5, while guessing 1 or 3 first needs 4.

Why take the max of the two sides?

The money must cover the worst case, so the secret is treated as an adversary that sends you to the more expensive side after a wrong guess.

What is the time complexity?

O(n cubed) time and O(n squared) memory: O(n squared) ranges, each trying up to n guesses.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP