Skip to content

Instantly share code, notes, and snippets.

@KeshariPiyush24
Created September 21, 2024 05:14
Show Gist options
  • Save KeshariPiyush24/9cb81ce55ca9b2f68fbab5a0b75d758b to your computer and use it in GitHub Desktop.
Save KeshariPiyush24/9cb81ce55ca9b2f68fbab5a0b75d758b to your computer and use it in GitHub Desktop.
374. Guess Number Higher or Lower

Question: 374. Guess Number Higher or Lower

Intution:

Time Complexity: $$O(log(n))$$

Space Complexity: $$O(1)$$

Solution:

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int low = 1;
        int high = n;
        
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (guess(mid) == 0)
                return mid;
            else if (guess(mid) == -1)
                high = mid - 1;
            else
                low = mid + 1;
        }
        
        return low;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment