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.