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.