Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 167 · Two Pointers

Two Sum II - Input Array Is Sorted

LeetCode 167 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Sorted ⇒ two pointers squeeze toward the target.

நடுத்தரம்ArrayTwo PointersBinary Search
LeetCode இல் திற ↗

நான் 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. 1

    left = 0, right = n − 1.

  2. 2

    Sum equals target → return 1-based indices.

  3. 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.