Skip to content

Latest commit

 

History

History
90 lines (65 loc) · 3.26 KB

374.Guess_Number_Higher_or_Lower(Easy).md

File metadata and controls

90 lines (65 loc) · 3.26 KB

374. Guess Number Higher or Lower (Easy)

Date and Time: Oct 13, 2024, 14:00 (EST)

Link: https://leetcode.com/problems/guess-number-higher-or-lower/


Question:

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

I pick a number from 1 to n. 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 int guess(int num), which returns three possible results:

  • -1: Your guess is higher than the number I picked (i.e. num > pick).

  • 1: Your guess is lower than the number I picked (i.e. num < pick).

  • 0: your guess is equal to the number I picked (i.e. num == pick).

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:

  • 1 <= n <= 2^31 - 1

  • 1 <= pick <= n


Walk-through:

Use l, r pointers to find the m = (l + r) // 2 and we use it to find either this guessing value is high or low. If high, we change the r pointer to be r = m - 1. If low, we change the l pointer to be l = m + 1. Return m when guess(m) == 0.


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:
        # Binary search to find n
        # l, r from 1 to n first, compare with m = (l + r) // 2
        # depends on output, change l, r to be 1 -> m-1 or m+1 -> r
        # until res == 0, return this m

        # TC: O(logn), SC: O(1)
        l, r = 1, n
        while l <= r:
            m = (l + r) // 2
            if guess(m) == 0:
                return m 
            # When guess is higher
            elif guess(m) == -1:
                r = m - 1
            # When guess is lower
            elif guess(m) == 1:
                l = m + 1

Time Complexity: $O(log\ n)$, n is the number we will try most, and this is binary search.
Space Complexity: $O(1)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms