Forem

ARUL SELVI ML
ARUL SELVI ML

Posted on

Guess the Number Higher or Lower

Guess the Number Higher or Lower

Problem Statement

We are playing a guessing game. The system picks a number between 1 and n. Your task is to guess the number.

You are given an API called guess which returns
-1 if your guess is higher than the picked number
1 if your guess is lower than the picked number
0 if your guess is correct

Find the picked number.


Example

Input
n = 10
picked number = 6

Output
6


Approach Using Binary Search

The idea is to reduce the search space by half in each step.


Steps

1 Start with the range from 1 to n
2 Find the middle value
3 Call guess with the middle value
4 If result is 0 return the number
5 If result is -1 search in the left half
6 If result is 1 search in the right half
7 Repeat until the number is found


Code

```python id="guess1"

The guess API is already defined

def guess(num):

def guessNumber(n):
left = 1
right = n

while left <= right:
    mid = (left + right) // 2
    result = guess(mid)

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



---

## Explanation

The algorithm uses binary search to efficiently find the number. At each step, it checks the middle value and narrows down the search range based on the response.

---

## Expected Output

Input
n = 10

Output
6

---

## Conclusion

This problem is a simple example of binary search. It helps in understanding how to reduce search space and improve efficiency.

Practice this problem to strengthen your understanding of searching techniques.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)