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.