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.