↻one more pass.
Two pointers · Medium

Two Sum II: the idea to remember.

Find a target sum pair in a sorted integer array using constant extra space. Return one based indices.

Solve on LeetCode ↗

The core insight

Compare the endpoints: move left for a sum that is too small and right for a sum that is too large.

Why it works

Sorted order lets us discard an endpoint: if even its largest partner is too small, that left value cannot work.

The mistake to avoid

The output is one based. The pointer movement relies on sorted input.

Time: O(n)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int[] twoSum(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left < right) {
        long sum = (long) nums[left] + nums[right];
        if (sum == target) return new int[]{left + 1, right + 1};
        if (sum < target) left++;
        else right--;
    }
    throw new IllegalArgumentException("No valid pair");
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.