Two ends
Inputs
values is a list of 0 to 12 whole numbers in increasing order, each from 0 to 40. target is a whole number from 0 to 80.
Your tasks
- Set
leftto 0 andrightto the last position. - Use a
whileloop that runs whileleft < right. If the two numbers add up totarget, return[left, right]. If the sum is too small, moveleftright. If it is too large, moverightleft. - Complete
twoSumSortedso it returns[left, right]for the first pair found this way, or[-1, -1]. Return it, do not print it.
Example
With values = [1, 3, 4, 8, 11] and target = 12, twoSumSorted returns [0, 4].
Rules
- Return
[-1, -1]when no pair adds up totarget. - The list is sorted, so the pair found by moving the two markers is the only one the tests ask for.
Test data
TEST DATA 1: values is [1, 3, 4, 8, 11], target is 12
TEST DATA 2: values is [2, 5], target is 100
Practice focus
Two pointers and sliding windows: loops that move two positions instead of one. Two pointers and sliding windows turn many quadratic answers into linear ones.