374. Guess Number Higher or Lower | LeetCode Using Python
I solved the “374. Guess Number Higher or Lower” problem from LeetCode using Python. By leveraging a binary search algorithm, I efficiently narrow down the range of possible numbers to identify the target in logarithmic time. This approach not only highlights the power of binary search but also provides a clear, step-by-step solution for those preparing for coding interviews or looking to improve their algorithmic skills.
Check out the video above for a detailed explanation and the Python code below:
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
# 1 if num is lower than the picked number
# otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
#We can easily and efficiently solve this with a binary search algorith
#Time Complexity O(log n)
#Space Complexity of O(1)
left_pointer, right_pointer = 1, n
while left_pointer <= right_pointer:
mid_point = (right_pointer + left_pointer) // 2
result = guess(mid_point)
if result == 0:
return mid_point
elif result == -1:
right_pointer = mid_point - 1
else: #1: Your guess is lower than the number I picked (i.e. num < pick).
left_pointer = mid_point + 1