← TopicsTwo Pointers · 1/9

Two Sum II — Sorted Array (Two Pointers)

You are given an array `nums` of integers sorted in strictly ascending order, and an integer `target`. Exactly one pair of distinct positions `i < j` satisfies `nums[i] + nums[j] == target`. Return the two 0-based indices `i` and `j` (with `i < j`). Use the two-pointers technique: start one pointer at each end, and move them inward based on how the current sum compares to the target. This runs in O(n) time and O(1) extra space. Batch IO: line 1 is the number of test cases T. Each of the next T lines is one case: `n target v1 v2 ... vn` (the length, the target, then the n sorted values). For each case print one line with the two indices separated by a space.

func twoSum(nums []int, target int) (int, int) {
left, right := 0, len(nums)-1
for left < right {
sum := nums[left] + nums[right]
if sum == target {
return left, right
}
if sum < target {
} else {
}
}
return -1, -1
}

this session — 0 attempt(s), 0 passed, 0 failed. (ephemeral; discarded when you leave)