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.