Python 3D Academyবাংলা

Pointers moving the same way: read and write

🌍 In real life. Mangoes roll along a conveyor at a packing house in Rajshahi. One worker, the reader, looks at every mango as it passes. A second worker, the writer, stands at the row of crates and only steps forward when the reader hands over a good one, placing it in the next empty crate. Both move the same way, but the writer moves only sometimes, so the good mangoes end up packed tightly at the front, in their original order, with no second conveyor needed.

The idea in one sentence: a read pointer R visits every item once, and a write pointer W marks where the next item worth keeping goes; everything left of W is the finished answer.

Its words:

  • read pointer: R, which visits every item once
  • write pointer: W, where the next item worth keeping goes; everything left of W is finished
  • in place: the answer is built inside the same list, with O(1) extra memory

Removing duplicates from a sorted list, in place, step by step:

  1. the first item is always kept, so W = 1
  2. for R = 1, 2, …: if nums[R] differs from the last kept value nums[W - 1], copy it to nums[W] and move W right
  3. otherwise it is a repeat: R moves on, W stays
  4. at the end, W is the number of different values, and nums[:W] holds them

Watch W lag behind R, filling the front with each value once:

Why it is correct. The invariant: nums[:W] holds every different value among nums[:R], once each, in order. At the start (W = R = 1) it holds the first value. Because the list is sorted, a repeat of anything kept would sit right next to the last kept value, so comparing nums[R] with nums[W - 1] is enough to spot it. Writing at W never overwrites anything still to be read, since W ≤ R.

What it costs. R moves n − 1 times and each step is O(1): O(n) time. Nothing new is built: O(1) extra memory, which matters when the list is huge. The easy way, sorted(set(nums)), makes new collections and costs O(n log n).

The same pattern solves many "keep some, drop some" jobs: moving all zeros to the end, removing a value, keeping only the passing marks.

def dedupe(nums):
    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

marks = [35, 35, 40, 72, 72, 90]
k = dedupe(marks)
print(k, marks[:k])
print(marks)            # what is past k is left over, not cleaned up

Mistakes and edge cases.

  • an empty list has no first item: return 0 before setting W = 1
  • comparing nums[R] with nums[R - 1] instead of the last kept value works here, but breaks for the "remove a value" variants; comparing with what you kept is the safe habit
  • nums.remove(x) inside a loop looks simpler but shifts the list every time (Chapter 34): O(n²)
  • the leftover items after position k are not deleted; slice with nums[:k] or del nums[k:]

Quiz

  1. What does this print?

    nums = [2, 2, 2, 5, 5, 9]
    w = 1
    for r in range(1, len(nums)):
        if nums[r] != nums[w - 1]:
            nums[w] = nums[r]
            w += 1
    print(w, nums[:w])
  2. Why does dedupe only compare with the last kept value?

    • The list is sorted, so any repeat sits right after the value it repeats
    • Python lists can only compare neighbours
    • It is a guess that is usually right
  3. What extra memory does the read/write version use?

    • O(1): just the two pointers
    • O(n): a second list
    • O(n): a set of seen values
  4. Moving zeros to the end with read and write: what does this print?

    nums = [0, 3, 0, 7, 1]
    w = 0
    for r in range(len(nums)):
        if nums[r] != 0:
            nums[w], nums[r] = nums[r], nums[w]
            w += 1
    print(nums)
  5. dedupe([]) answers 1, though an empty list has no values. Which line needs a check before it?

    def dedupe(nums):
        w = 1
        for r in range(1, len(nums)):
            if nums[r] != nums[w - 1]:
                nums[w] = nums[r]
                w += 1
        return w

Coding tasks

  1. Write dedupe(nums) for a sorted list, in place with a read and a write pointer: move each different value to the front, once, and give back how many there are (0 for an empty list). Don't build a new list.

  2. Write move_zeros(nums) in place, in one pass with a read and a write pointer: every non-zero keeps its order at the front, and the zeros go to the end. Give back the list.