InterviewHubPRO
Section Overview
Q20

Question 20 of 100

Part 3: Two Pointers & Sliding Window (19 - 28)

20%
DSA Patterns (Multi-Lang)•Part 3: Two Pointers & Sliding Window (19 - 28)

Two Sum II (Input Array Is Sorted).

In Simple Words: Left pointer at 0, right pointer at $N-1$. If nums[l] + nums[r] < target, increment l; if greater, decrement r.

  • Time: $O(N)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def twoSum(numbers: list[int], target: int) -> list[int]:
    l, r = 0, len(numbers) - 1
    while l < r:
        curr = numbers[l] + numbers[r]
        if curr == target:
            return [l + 1, r + 1]  # 1-indexed
        elif curr < target:
            l += 1
        else:
            r -= 1
    return []