EasyNo. 0374
Guess Number Higher or Lower — LeetCode 374 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Binary Search, Interactive
- On a study list
- LeetCode 75
- Reading time
- 2 min
- Source
- leetcode.com
The problem
We are playing the Guess Game. The game is as follows: I pick a number from 1 to n.
Example
- Input
- n = 10, pick = 6
- Output
- 6
Python solution
# 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:
return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x))Complexity
- Time
- O(log n)where n is the upper limit given in the problem
- Space · auxiliary
- O(1)
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 374. Guess Number Higher or Lower is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0375 | Guess Number Higher or Lower II | Medium |
| 0278 | First Bad Version | Easy |
| 1095 | Find in Mountain Array | Hard |
| 0378 | Kth Smallest Element in a Sorted Matrix | Medium |
| 0367 | Valid Perfect Square | Easy |
| 0004 | Median of Two Sorted Arrays | Hard |
Frequently asked questions
- How hard is LeetCode 374. Guess Number Higher or Lower?
LeetCode 374. Guess Number Higher or Lower is rated Easy on LeetCode.
- What is the time complexity of LeetCode 374. Guess Number Higher or Lower?
The Python solution on this page runs in O(log n), where n is the upper limit given in the problem.
- What is the space complexity of LeetCode 374. Guess Number Higher or Lower?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 374. Guess Number Higher or Lower cover?
LeetCode 374. Guess Number Higher or Lower is tagged Binary Search and Interactive on LeetCode.