Algorithmsbranching

Two Pointer Branching — Conditional Moves

TT
Testlaa Team
May 14, 20261 min read

Branching means multiple cases (if/elif) for moves: e.g. remove duplicates in-place, or partition colors. Each branch must shrink the search space safely.

Try this in Python

def remove_duplicates_sorted(nums: list[int]) -> int:
    if not nums:
        return 0
    w = 1
    for r in range(1, len(nums)):
        if nums[r] != nums[w - 1]:
            nums[w] = nums[r]
            w += 1
    return w


a = [1, 1, 2, 2, 3]
k = remove_duplicates_sorted(a)
print(k, a[:k])

Key takeaways

  • Fast (write) and slow (read) pointers are a branching pattern.
  • Invariant: first w cells are unique in order.
  • Practice tracing r and w.

Tags:

Two pointersPythonStudents