Binary Search
LeetCode 704 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Halve [low, high] around mid until found or empty.
నేను Binary Search (LeetCode 704) ను ఇలా పరిష్కరించాను — Basics / Lower & Upper Bound ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
In a sorted array, comparing the target with the middle element rules out half of the remaining range every step.
Approach
- 1
low = 0, high = n − 1.
- 2
mid = (low + high) // 2.
- 3
Equal → return mid; target bigger → low = mid + 1; smaller → high = mid − 1.
- 4
Empty range → −1.
నేను ఎలా పరిష్కరించాను
Iterative binary searchPythonO(log n) time · O(1) space
class Solution:
def search(self, nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target == nums[mid]:
return mid
if target > nums[mid]:
low = mid + 1
else:
high = mid - 1
return -1Binary Search — తరచూ అడిగే ప్రశ్నలు
Binary Search వెనుక ఉన్న intuition ఏమిటి?
In a sorted array, comparing the target with the middle element rules out half of the remaining range every step.
Binary Search (LeetCode 704) ను ఎలా పరిష్కరించాలి?
1. low = 0, high = n − 1. 2. mid = (low + high) // 2. 3. Equal → return mid; target bigger → low = mid + 1; smaller → high = mid − 1. 4. Empty range → −1.
Binary Search యొక్క time, space complexity ఎంత?
Time: O(log n). Space: O(1). (Accepted approach: Iterative binary search.)
Binary Search లో సాధారణ పొరపాట్లు ఏమిటి?
Use low ≤ high so single-element ranges are checked.