Python coding

Target-sum pair in a sorted list

nums is sorted in non-decreasing order and may repeat values. Return the positions [i, j], with i < j, of the two numbers that add up to target. At most one pair of positions works; if none does, return []. Positions start at 0.

Aim for O(n) time and O(1) extra space: the sorted order replaces a hash map.

Besides the tests, one large input (6,000 sorted numbers) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • pair_in_sorted([1,4,6,9,13], 15) → [2,3]
  • pair_in_sorted([-5,-1,0,3,8], 7) → [1,4]
  • pair_in_sorted([1,2,4], 4) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Put lo on the first index and hi on the last, and compare nums[lo] + nums[hi] with target.

Hint 2

Too small: only a bigger left value can help, so lo += 1. Too big: hi -= 1. Stop when they meet: a number can't pair with itself.

Solution and why it works
pythonO(n) · O(1)
def pair_in_sorted(nums: list[int], target: int) -> list[int]:
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return [lo, hi]
        if s < target:
            lo += 1          # nums[lo] is too small even with the largest value left
        else:
            hi -= 1          # nums[hi] is too big even with the smallest value left
    return []

Sorted order makes every comparison decisive. If nums[lo] + nums[hi] is too small, nums[lo] falls short even with the largest value left, so no answer uses it; if too big, nums[hi] is out. One end moves per step: O(n) time and O(1) space, versus O(n²) pairs. Loop while lo < hi, not <=: with [1, 2, 4] and target 4, 2 + 2 would use one position twice.

Related lab: Loops in motion