Same-direction vs opposite-end pointers

Two pointers Junior Python 3.13+ Reviewed By Best Latest Apps

Predict the output

Both loops scan 6 items. What does this print?

Python 3.13
a = [1, 2, 3, 4, 5, 6]
lo, hi, moves = 0, len(a) - 1, 0
while lo < hi:
    lo += 1
    moves += 1
slow = 0
for fast in range(len(a)):
    if a[fast] % 2 == 0:
        slow += 1
print(moves, slow)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 5 3

Right: the opposite pointers meet after 5 moves, and 3 even values move the slow pointer.

Neither pointer ever goes back, so the total moves stay within a small multiple of n.

Why not the others?
  • B 6 6. The slow pointer only moves on even values.
  • C 3 3. Only lo moves here, so it takes 5 steps to meet hi.

30-second answer

Opposite-end pointers start apart and close in; each step drops one end, so they finish in at most n steps. Same-direction pointers both move forward: the fast one reads, the slow one writes or marks a window start, and each moves at most n times. Both are O(n) because no pointer ever moves backwards.

Practise saying it · 45 s. No recording, just a timer

Compare the two pointer styles and why both are linear.

Say your answer out loud, then check which of these points you covered:

  • Opposite ends close in
  • Same direction: reader and writer
  • Total moves bounded by 2n

Deep dive

Opposite ends: pair sums, reading both ways, sorted squares, container-style area questions.

Same direction: removing items in place, deduplication, sliding windows, fast and slow pointers on linked lists.

The O(n) argument is a counting one: total pointer moves are bounded by 2n.

Common mistakes

  • Thinking the inner while loop of a window makes it O(n²): the left pointer moves at most n times in total.
  • Mixing the two styles in one loop without a clear invariant.

Senior take & follow-ups

Use the 'total moves' argument; it is the standard way to prove these loops are linear.

Follow-up questions

Think of your answer first, then open the hint.

  1. Where do fast and slow pointers fit?

    Show hint

    Same direction, different speeds: finding a middle or a loop in a linked list.

  2. Can a pointer move backwards?

    Show hint

    Then the 2n bound breaks; re-check the cost.

What each operation costs: Arrays · Array Operations

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.