Good evening! Here's our prompt for today.
The setup is the same as Two Sum-- you're given an array of numbers, and a "goal" number.
Write a method to return an array of the indexes of the two elements in the array that sum up to the goal. If there are no such elements, return an empty array.
The caveat here is that the numbers are guaranteed to be sorted.

So let's say our goal number was 10
. Our numbers to sum to it would be 3
and 7
, and their indices 1
and 2
respectively.
1let arr = [1, 3, 7, 9, 11];
2let goal = 10;
3twoSum(arr, goal);
4// [1, 2]
Is there an efficient way to figure this out?
Constraints
- Length of the array <=
100000
- The array will always contain integer values between
-1000000000
and1000000000
- The required sum is will be well within the integer range
- Expected time complexity :
O(n)
- Expected space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
def sorted_two_sum(nums, goal):
# fill in
return nums
​
​
import unittest
​
​
class Test(unittest.TestCase):
def test_1(self):
assert sorted_two_sum([3, 6, 13, 14], 16) == [0, 2]
print("PASSED: `sorted_two_sum([3, 6, 13, 14], 16)` should return `[0, 2]`")
​
def test_2(self):
assert sorted_two_sum([1, 9, 13, 20, 47], 67) == [3, 4]
print("PASSED: `sorted_two_sum([1, 9, 13, 20, 47], 67)` should return `[3, 4]`")
​
def test_3(self):
assert sorted_two_sum([1, 9, 13, 20, 47], 6) == []
print("PASSED: `sorted_two_sum([1, 9, 13, 20, 47], 6)` should return `[]`")
​
​
if __name__ == "__main__":
unittest.main(verbosity=2)
print("Nice job, 3/3 tests passed!")
​
Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.