MediumTrees
Validate Binary Search Tree
Check if tree is valid BST
Solution Approach
Divide search space in half repeatedly. Apply binary search on sorted arrays or search space. Check middle element and adjust bounds based on comparison.
Implementation
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1Complexity Analysis
Time Complexity
O(log n)Space Complexity
O(1)Key Learning Points
Divide search space by 2Only works on sorted dataPrevent integer overflow with mid calculation
Related Problems to Practice
Binary SearchSearch in Rotated ArrayFind First/Last Position
Complexity
Time:O(log n)
Space:O(1)
Asked at
GoogleAmazonMicrosoft