---
# System prepended metadata

title: LC 374. Guess Number Higher or Lower
tags: [easy, leedcode, Binary Search, python]

---

# LC 374. Guess Number Higher or Lower

### [Problem link](https://leetcode.com/problems/guess-number-higher-or-lower/)

###### tags: `leedcode` `python` `easy` `Binary Search`

We are playing the Guess Game. The game is as follows:

I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:

- <code>-1</code>: Your guess is higher than the number I picked (i.e. `num > pick`).
- <code>1</code>: Your guess is lower than the number I picked (i.e. `num < pick`).
- <code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).

Return the number that I picked.

**Example 1:** 

```
Input: n = 10, pick = 6
Output: 6
```

**Example 2:** 

```
Input: n = 1, pick = 1
Output: 1
```

**Example 3:** 

```
Input: n = 2, pick = 1
Output: 1
```

 **Constraints:** 

- <code>1 <= n <= 2<sup>31</sup> - 1</code>
- <code>1 <= pick <= n</code>


## Solution 1 - Binary Search
```python=
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
#          1 if num is lower than the picked number
#          otherwise return 0
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        left, right = 1, n

        while left <= right:
            mid = (left + right) // 2
            if guess(mid) == 0:
                return mid
            elif guess(mid) == 1:
                left = mid + 1
            else:
                right = mid - 1
```

>### Complexity
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(logn)         | O(1)             |


## Note
x
