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.