Two Sum II - Input Array Is Sorted
LeetCode 167 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Sorted ⇒ two pointers squeeze toward the target.
আমি Two Sum II - Input Array Is Sorted (LeetCode 167) এভাবে সমাধান করেছি — Two Pointers প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Because the array is sorted, start with the smallest and largest values. If their sum is too small, the only way up is to move the left pointer right; too big, move the right pointer left.
Approach
- 1
left = 0, right = n − 1.
- 2
Sum equals target → return 1-based indices.
- 3
Sum too small → left += 1; too big → right −= 1.
আমি কীভাবে সমাধান করেছি
Two pointersPythonO(n) time · O(1) space
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left = 0
right = len(numbers)-1
while left<right:
cur_sum = numbers[left]+numbers[right]
if cur_sum==target:
return [left+1,right+1]
elif cur_sum<target:
left+=1
else:
right-=1
Two Sum II - Input Array Is Sorted — সাধারণ প্রশ্ন
Two Sum II - Input Array Is Sorted-এর পেছনে intuition কী?
Because the array is sorted, start with the smallest and largest values. If their sum is too small, the only way up is to move the left pointer right; too big, move the right pointer left.
Two Sum II - Input Array Is Sorted (LeetCode 167) কীভাবে সমাধান করবেন?
1. left = 0, right = n − 1. 2. Sum equals target → return 1-based indices. 3. Sum too small → left += 1; too big → right −= 1.
Two Sum II - Input Array Is Sorted-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: Two pointers।)
Two Sum II - Input Array Is Sorted-এ সাধারণ ভুলগুলো কী?
The answer is 1-indexed.