DEV Community

Sandhya Steffy M
Sandhya Steffy M

Posted on

Guess Number Higher or Lower Using Binary Search

Problem Statement:
We need to guess a number between 1 and n using a given API that tells whether the guess is higher, lower, or correct.

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

Approach:
We use Binary Search to efficiently find the number. At each step, we check the middle value and adjust the search range based on the API response.

Code:

def guessNumber(n):
low = 1
high = n

while low <= high:
    mid = (low + high) // 2
    result = guess(mid)

    if result == 0:
        return mid
    elif result == -1:
        high = mid - 1
    else:
        low = mid + 1
Enter fullscreen mode Exit fullscreen mode

Explanation:
The algorithm repeatedly halves the search space using binary search. This ensures the number is found efficiently.

Time Complexity:
O(log n)

Space Complexity:
O(1)

Top comments (0)