Two pointers on sorted data

When the data is sorted, two indices moving through it can replace a nested loop. Each step moves one pointer, so the whole scan is O(n).

The classic form starts at both ends to find a pair with a target sum:

i, j = 0, len(nums) - 1
while i < j:
    s = nums[i] + nums[j]
    if s == target: return i, j
    if s < target: i += 1
    else: j -= 1

Another form has a slow pointer that writes and a fast pointer that reads. That is how you remove duplicates in place.

The signal: sorted input, pairs, or "in place with O(1) extra space".

A common mistake: deleting with del nums[i] inside the loop. Every delete shifts the rest of the list, so the loop becomes O(n²).

Exercise: finish dedupe_sorted. It gets a sorted list, moves the unique values to the front in order, and returns how many there are. Only nums[:k] is checked. Use O(1) extra space and O(n) time. Press Check to run the tests.