Workspace Two Sum Ii
0d
DSA Problem Sheet

Two Sum in a Sorted Array

In sorted input return indices of a pair summing to the target, or an empty array. Resolve ties with the earliest left index and latest matching right index.

EXECUTION LAB

In sorted input return indices of a pair summing to the target, or an empty array. Resolve ties with the earliest left index and latest matching right index.

Input and constraints
  • Values must be in nondecreasing order.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
left = 0
right = (len(values) - 1)
while (left < right):
total = (values[left] + values[right])
if (total == target):
return [left, right]
if (total < target):
left = (left + 1)
else:
right = (right - 1)
return []

Visualizer

Step 1 of 2
01left
13
24
37
49right

Inspect the current state

Compare pair sum 10 with 10.

Variable watch

left 0right 4total 10target 10

Step explanation

Compare pair sum 10 with 10.

comparisons 1reads 2writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

Adjust two ends of a balance scale, moving only the side whose change improves the total.

Guided solution

If the sum is too small, the left item cannot work with any remaining partner. A too-large sum rules out the right item.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[1,3,4,7,9],"target":10} ⇒ [0,4]

Edge case 1 · {"values":[3],"target":6} ⇒ []

Edge case 2 · {"values":[],"target":2} ⇒ []

Progressive hints

Hint 1Adjust two ends of a balance scale, moving only the side whose change improves the total.
Hint 2If the sum is too small, the left item cannot work with any remaining partner. A too-large sum rules out the right item.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Identical values still require two distinct positions.

Interview follow-up

Why is sorted order essential to this elimination?