EasyNo. 0374

Guess Number Higher or Lower — LeetCode 374 Python Solution

Topics
Binary Search, Interactive
On a study list
LeetCode 75
Reading time
2 min

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

PythonSolution
# 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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.