DEV Community

loading...

Day-20 Guess Number Higher or Lower πŸ‘©β€πŸ’»

mridubhatnagar profile image Mridu Bhatnagar ・2 min read

For the last 19 days, I am making sure to solve at least a problem a day. I got stuck at optimizing a problem named Rotate Array yesterday. And, as a result, couldn't solve a problem, could not write. I am still stuck at the same problem. Meanwhile, I solved a new one.

Background

This problem statement is a part of LeetCode's learn card titled Binary Search. Under the sub-heading Binary Search Template-I.

Problem Statement

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'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!
Example
Input: n = 10, pick = 6
Output: 6
Solution Approach
  1. start = 1, end = n+1. (See the problem statement. Numbers from 1 to n. Hence, make sure both are inclusive).
  2. calculate mid. mid = int((start+end)/2)
  3. Now pass mid as parameter to the guess API.
  4. Divide the list based on the value returned by API.
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:

class Solution:
    def guessNumber(self, n: int) -> int:
        start = 1
        end = n+1
        while start < end:
            mid = int((start+end)/2)
            if guess(mid) == -1:
                end = mid
            elif guess(mid) == 1:
                start = mid + 1
            elif guess(mid) == 0:
                return mid
        return -1
Learnings
  1. The time complexity of the above solution is - O(logn).
  2. When in the problem statement it is already mentioned sorted array think binary search.
  3. Time complexity of Binary Search - O(logn). Time complexity of Linear Search - O(n). Binary search is more efficient.

Discussion

pic
Editor guide