Skip to content
Problem 374 · LeetCode 374(opens in a new tab)

Guess Number Higher or Lower

EasyBinary search

A number pick has been chosen from 1 to n, and you must find it. You cannot see it; you can only call a provided function guess(num), which returns −1 if pick is lower than num, 1 if pick is higher, and 0 if num is the pick.

Return the chosen number.

Example 1

Input:  n = 16, pick = 13
Output: 13
Why:    guesses 8 (higher), 12 (higher), 14 (lower), 13 (correct)
2 more examples and the constraints

Example 2

Input:  n = 5, pick = 5
Output: 5
Why:    the pick can be n itself

Example 3

Input:  n = 3, pick = 1
Output: 1
Why:    the pick can be 1 as well

Constraints

  • 1 ≤ n ≤ 2³¹ − 1 (2,147,483,647)
  • 1 ≤ pick ≤ n

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Ternary searchO(log n)
  2. Binary searchO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeWorst-case guesses for n = 2³¹ − 1Verdict
Ternary searchO(log n)
Passes; about 40 guesses
Binary searchO(log n)
Best; at most 31 guesses

n = the top of the range. Counting up from 1 would be O(n): up to 2 billion guesses.

Edge cases to test

  • n = 1. The only possible pick is 1, and the first guess finds it.
  • Pick at either end. pick = 1 or pick = n must still be reached; the range shrinks onto the end.
  • Largest n. With n = 2,147,483,647 and a high pick, (lo + hi) / 2 overflows a 32-bit int.
  • Reply sign. −1 means the pick is lower than the guess, not that the guess is lower.

Common mistakes

  • Computing mid as (lo + hi) / 2, which overflows in Java and C++ for large n.
  • Reading −1 as "guess higher" and moving the wrong bound.
  • Setting lo = mid or hi = mid instead of mid ± 1, which can loop forever.

How to talk through it

  1. 1Clarify. What exactly do −1 and 1 mean? Is the pick always in range? How big can n be?
  2. 2Give the brute force. Guess 1, 2, 3 and so on: O(n), up to 2 billion calls.
  3. 3Name the search. Every reply says which side the pick is on, so halve the range each time: binary search.
  4. 4Code it safely. mid = lo + (hi − lo) / 2, and move lo or hi past mid by one.
  5. 5Test out loud. Run n = 1, pick = 1, pick = n and n = 2³¹ − 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?