DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Guess Number Higher or Lower – Python (Binary Search)

🎯 Guess Number Higher or Lower – Python (Binary Search)

Hi All,

Today I solved a fun and important problem: Guess Number Higher or Lower using Binary Search.


📌 Problem Statement

We are given a number range from 1 to n.

👉 A number is already picked (hidden), and we need to guess it.

We use a predefined function:

guess(num)
Enter fullscreen mode Exit fullscreen mode

It returns:

  • -1 → Your guess is too high
  • 1 → Your guess is too low
  • 0 → Correct guess

💡 Approach

🔹 Binary Search (Optimal)

👉 Idea:

  • Search in the range [1, n]
  • Use middle element
  • Reduce search space based on result

🧠 Step-by-Step Logic

  1. Set:

    • low = 1
    • high = n
  2. Find middle:

   mid = (low + high) // 2
Enter fullscreen mode Exit fullscreen mode
  1. Call guess(mid):
    • If 0 → return mid
    • If -1 → search left (high = mid - 1)
    • If 1 → search right (low = mid + 1)

💻 Python Code

class Solution:
    def guessNumber(self, 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

🔍 Example Walkthrough

Input:

n = 10
pick = 6
Enter fullscreen mode Exit fullscreen mode

Steps:

  • mid = 5 → guess(5) = 1 → go right
  • mid = 8 → guess(8) = -1 → go left
  • mid = 6 → guess(6) = 0 → found

🖥️ Sample Output

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

Input: n = 1, pick = 1
Output: 1

Input: n = 2, pick = 1
Output: 1
Enter fullscreen mode Exit fullscreen mode

⚡ Complexity Analysis

  • Time Complexity: O(log n)
  • Space Complexity: O(1)

🧠 Why this is important?

  • Classic Binary Search problem
  • Reduces search space efficiently
  • Very common in interviews

✅ Conclusion

This problem helped me understand:

  • Binary search logic
  • Efficient searching
  • Problem-solving using API-based hints

🚀 A must-know problem for beginners!


Top comments (0)