High interview relevanceRoadmap: Beginner
TimeO(n)
SpaceO(1)

Why it costs this much

Each pointer only moves in one direction, so together they make at most n moves.

Code

def pair_sum(sorted_nums, target):
    lo, hi = 0, len(sorted_nums) - 1
    while lo < hi:                  # lo and hi only move inward: at most n steps
        s = sorted_nums[lo] + sorted_nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None

Common pitfalls

It needs sorted or otherwise ordered input, and sorting first adds O(n log n). Be able to explain why moving a pointer cannot skip the answer.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list