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.