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

मैंने 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.