Remove Duplicates In Place

Step 4: Remove Duplicates In Place

Implement remove_duplicates(sorted_nums) on a list sorted in non-decreasing order. Remove duplicates in place so that the first k elements are unique, and return the new length k.

Use a slow pointer marking the last unique position and a fast pointer scanning forward. When the fast value differs from the slow value, advance slow and copy the value there. An empty list returns 0.

Hints
Starter code
def two_sum_sorted(nums, target):
    i, j = 0, len(nums) - 1
    while i < j:
        s = nums[i] + nums[j]
        if s == target:
            return (i, j)
        elif s < target:
            i += 1
        else:
            j -= 1
    return None


def is_palindrome(s):
    i, j = 0, len(s) - 1
    while i < j:
        while i < j and not s[i].isalnum():
            i += 1
        while i < j and not s[j].isalnum():
            j -= 1
        if s[i].lower() != s[j].lower():
            return False
        i += 1
        j -= 1
    return True


def reverse_in_place(arr):
    i, j = 0, len(arr) - 1
    while i < j:
        arr[i], arr[j] = arr[j], arr[i]
        i += 1
        j -= 1
    return arr


def remove_duplicates(sorted_nums):
    """Remove duplicates in place; return new length k of the unique prefix."""
    # TODO: use a slow pointer and a fast pointer to overwrite duplicates
    pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.