Magicsheet logo

Guess Number Higher or Lower II

Medium
25%
Updated 8/1/2025

Guess Number Higher or Lower II

What is this problem about?

The Guess Number Higher or Lower II interview question is a "Medium" variation of the previous game, but with a twist. This time, every time you guess a number x and you are wrong, you must pay $x. You need to find out how much money you need to guarantee a win, regardless of what the secret number is. This means you must find the minimum cost of the worst-case scenario.

Why is this asked in interviews?

Google asks this Game Theory and Dynamic Programming problem to test a candidate's ability to model Min-Max algorithms. It evaluates your understanding of "worst-case" scenarios. You want to minimize the cost, but for any chosen strategy, nature will choose the secret number that maximizes your cost. It requires a 2D DP table to represent sub-ranges.

Algorithmic pattern used

This problem uses 2D Dynamic Programming (Min-Max).

  1. Define dp[i][j] as the minimum cost to guarantee a win in the range [i, j].
  2. Base case: If i >= j, dp[i][j] = 0 (no guesses needed, you know the number).
  3. Transition: For a range [i, j], if you guess x (where ixji \le x \le j), the worst-case cost is x + max(dp[i][x-1], dp[x+1][j]).
  4. Since you play optimally, you want to pick the x that minimizes this worst-case cost: dp[i][j] = min_over_x(x + max(dp[i][x-1], dp[x+1][j])).

Example explanation

Range [1, 3]:

  • Guess 1: Cost 1+max(dp[0,0],dp[2,3])=1+max(0,2)=31 + \max(dp[0,0], dp[2,3]) = 1 + \max(0, 2) = 3.
  • Guess 2: Cost 2+max(dp[1,1],dp[3,3])=2+max(0,0)=22 + \max(dp[1,1], dp[3,3]) = 2 + \max(0, 0) = 2.
  • Guess 3: Cost 3+max(dp[1,2],dp[4,3])=3+max(1,0)=43 + \max(dp[1,2], dp[4,3]) = 3 + \max(1, 0) = 4. The minimum of these worst-case costs is 2. So, if you guess 2 first, you spend $2 and either win immediately, or know exactly whether the answer is 1 or 3 without paying more.

Common mistakes candidates make

  • Binary Search Fallacy: Assuming that guessing the middle element (like standard binary search) is always the cheapest strategy. It's not, because larger numbers cost more, so the optimal guess is usually skewed towards the right.
  • Forgetting the Max: Simply summing the costs of both halves instead of taking the maximum, which is required to cover the worst-case scenario.
  • Index out of bounds: Not handling the DP transitions carefully when x=ix=i or x=jx=j.

Interview preparation tip

"Minimize the maximum loss" or "Guarantee a win" are classic signs of Min-Max DP. Practice setting up the loops: typically, you iterate over the length of the range first, then the start index, to ensure subproblems are solved before larger ones.

Similar Questions