easy +10 pts

Two Sum Sorted

Find two indices in a sorted array whose values sum to a target.

Write a function `two_sum_sorted(nums, target)` that takes a list of integers `nums` sorted in non-decreasing order and an integer `target`. The function must return a list of the two indices (1-based) of the two numbers that sum to `target`. Exactly one solution is guaranteed, and you may not use the same element twice. Your solution should run in O(n) time and O(1) extra space.

Constraints

2 <= len(nums) <= 10^4 -10^5 <= nums[i] <= 10^5 -10^5 <= target <= 10^5 Exactly one valid answer exists. The array is sorted in non-decreasing order.

Example

>>> two_sum_sorted([2,7,11,15], 9)
[1,2]
>>> two_sum_sorted([2,3,4], 6)
[1,3]
>>> two_sum_sorted([-1,0], -1)
[1,2]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use two pointers: one at the start, one at the end.
If the current sum is too small, move the left pointer right; if too large, move the right pointer left.
Remember the indices are 1-based in the output.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.