iq.lab
Python starts when a code cell comes near or you run one
04 Two pointers and sliding windows

Lesson 2 of 4

Read and write pointers

Two indexes walk one list in the same direction. `read` looks at every item, `write` marks where the next kept item goes, and everything before `write` is already the finished answer. Filled from the back, the same idea merges two sorted lists in place.

About 1 hour 35 minutes, with the 3 problems worked in it
By the end you can
  • Explain why deleting items one at a time from a Python list can cost O(n2) time

  • Filter a list in place with a read pointer and a write pointer, and say the promise that makes it safe

  • Drop repeats from a sorted list by comparing each item with the last value kept

  • Swap instead of copy when the skipped items must stay in the list

  • Merge two sorted lists in place by filling from the back

  • Spot a read and write problem from its wording (in place, return the new length, merge into the first list)

A sensor sends one reading a minute, and a negative reading is an error code: -1 means the sensor was offline, -2 means the value was out of range. Here are five minutes of it: [3, -1, 5, -2, 8]. Before any analysis, the error codes have to go.

At work this is one line: WHERE reading >= 0 in SQL, or [x for x in readings if x >= 0] in Python. Both build a second list for the answer, and at work that is usually the right call.

Interview versions of this task add two words: in place. In place means you change the list you were given, inside that same list, using a few extra names and no second list. All three problems in this lesson say it, and they test one skill: rewriting a list while you walk it, without destroying an item you still need.

The tool is a second index. In the last lesson two indexes walked inward from both ends. Here both walk the same way, one behind the other: one reads, one writes. But start with the idea most people try first, and see why it fails.

Deleting as you go

What goes wrong if we delete each error code the moment we meet it? Python lists have nums.pop(i), which removes the item at position i. The walk below uses a while loop, because after a deletion the next item slides into position i, and the loop must look at it without moving. The trace uses four readings, with two error codes side by side. Before you step through, guess: after the first pop, which number sits at position 1?

Step throughDeleting as you go
Step 1 of 17
Line 1 is about to run.
nums = [3, -1, -2, 8]
i = 0
while i < len(nums):
if nums[i] < 0:
nums.pop(i)
else:
i += 1
print(nums)
Names
no names yet
Output
(nothing printed yet)

pop(i) is one line, but it is not one step. A list keeps its items in consecutive slots of memory (module 3), so removing one leaves a gap, and Python closes the gap by moving every later item one slot left. The first pop above moved two items, the -2 and the 8. The second moved one, the 8.

With many error codes, those moves add up to O(n2) time. A list of n readings can need up to n deletions, and each can move up to n items. O(n2) means the work grows with the square of the length: twice the readings, four times the work. Count it yourself on a small case.

Work it outWhat the deletions cost

Follow the delete-as-you-go loop from the trace on [-1, 4, -1, 4, -1, 4, -1, 4]: eight readings, every other one an error code. Each nums.pop(i) moves every item after position i one slot left. How many item moves do all the pops make in total? Type a whole number.

moves

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

There is a second way to get deletion wrong, and it is easier to fall into.

Here is the trap in action. nums.remove(x) deletes the first item equal to x. Predict the output before you check.

PredictThe item the loop never saw

This version deletes inside a for loop. nums.remove(x) deletes the first item equal to x. Type exactly what it prints.

nums = [-1, -2, 4, -3]
for x in nums:
    if x < 0:
        nums.remove(x)
print(nums)

Both problems come from closing each gap the moment it opens. The fix never opens a gap: it moves the good items forward instead of pulling the bad ones out.

A read pointer and a write pointer

Instead of deleting the bad items, copy the good ones forward. As in the last lesson, a pointer is an index that marks a position in the list. We walk with two of them. read visits every position once, left to right. write is the slot where the next kept item goes, so everything before write is finished. We call that finished part nums[:write]: the slice from position 0 up to, but not including, write. Before you step through, guess the list when the function returns. Is the -1 still in it?

Step throughKeep the good readings, in place
Step 1 of 22
Line 1 is about to run.
def keep_valid(nums):
write = 0
for read in range(len(nums)):
if nums[read] >= 0:
nums[write] = nums[read]
write += 1
return write
Names
no names yet
Output
(nothing printed yet)

The -1 is gone: the 5 was written over it. Here is the sentence that makes this code right:

The promise talks about the list as it arrived, because the copies change slots as the walk goes. After three passes the list reads [3, 5, 5, -2, 8] and write is 2. The first three readings as they arrived were 3, -1 and 5. The kept ones are 3 and 5, and nums[:2] holds exactly those.

Writing is safe because write never passes read. Each pass moves read one step and write at most one step. So every copy lands on the slot being read right now or on one the walk has already passed, and no item still waiting to be read is overwritten.

When the walk ends, the promise is the answer. read has passed every item, so nums[:write] holds every kept item, in order. The slots after it (-2, 8 here) are leftovers, and the function returns write so the caller knows where the answer stops. On an empty list the loop never runs and the function returns 0. The first problem in this lesson uses the same contract: return the count, and only that many slots at the front are checked.

Now build it yourself with a different keep rule, the test that decides which items stay: remove every copy of one value. The lines are all here, in the wrong order.

Put in orderRemove every copy of a value

Put the lines in order to build remove_value(nums, val). It moves every item that is not val to the front of nums, in their original order, and returns how many there are. Indentation is already part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • return write
    • write += 1
    • def remove_value(nums, val):
    • nums[write] = nums[read]
    • nums.pop(read)
    • if nums[read] != val:
    • for read in range(len(nums)):
    • write = 0
    • return nums

    And once more, this time writing the whole body yourself. This one has a trap that data engineers know well.

    Code itDrop the missing values

    A column arrives as a list with None where a value is missing. Write drop_nulls(values), which moves every value that is not None to the front of the same list, in order, and returns how many there are. Do not build a second list. A 0 is a real value, not a missing one. Then press Watch it run to see both pointers move.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Keeping each value once

    How do you drop repeats from a sorted list, in place? Take [1, 1, 2, 3, 3]. The goal: the first three slots become [1, 2, 3], and the function returns 3. A set of the values kept would spot repeats, but it is a second container that can grow to n items: O(n) extra space. The sorted order gives a cheaper test.

    The walk and the notebook stay the same; only the keep rule changes. Keep an item when the finished part does not hold its value yet. The list is sorted, so equal values sit side by side, and nums[:write] holds the kept values, smallest first. So one comparison is enough. Which one?

    Quick checkIs this value new?

    The list is sorted and write starts at 1, so nums[:write] holds the values kept so far, smallest first. At position read, which test says nums[read] is a value we have not kept yet, with one comparison?

    Choose one answer, then check.

    Compare with the last value kept, nums[write - 1]. It is the largest value kept so far, so it is the only kept value that the item at read could equal.

    Both pointers start at 1, and an empty list returns 0 first. The first item is always new, and it is already in the right slot, so both read and write start at 1. An empty list has no first item, so the function returns 0 before the loop. Without that check, write would start at 1 and the function would return 1 for a list with nothing in it. Trace it by hand once before you write it: in a round with no run button, this table is how you test.

    On paperDrop the repeats by hand

    Trace the repeat remover on paper for nums = [2, 2, 5, 5, 5, 7]. write starts at 1 and read goes from 1 to 5. An item that differs from nums[write - 1] is copied to nums[write], and then write grows by 1. Keep a table with one row per read: the item, the last kept value nums[write - 1], what happens, and write afterwards. Reveal the steps one at a time to check your rows, then type write at the end.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    write at the end

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Now write it. The tests check the returned count, k, and the first k slots, nums[:k].

    easyTwo pointers target 15 min

    Remove duplicates from a sorted list

    The list of integers nums is sorted from smallest to largest, so equal values sit next to each other. A value may appear more than once.

    Rearrange nums in place (inside the same list, using only a few extra variables) so that its first k positions hold each different value once, smallest first. Here k is the number of different values in the list. Return k.

    The tests check the returned k and nums[:k]. Whatever is left from position k onward does not matter.

    Example 1
    Inputnums = [1, 1, 2, 3, 3]Output3, and nums begins [1, 2, 3]

    Three different values: 1, 2 and 3. The two items after them can hold anything.

    Example 2
    Inputnums = [0, 0, 0, 1, 4, 4, 5]Output4, and nums begins [0, 1, 4, 5]

    The three 0s become one 0, and the two 4s become one 4.

    Example 3
    Inputnums = [2, 3, 7]Output3, and nums stays [2, 3, 7]

    No value repeats, so every item stays where it is.

    Constraints
    • 0 ≤ len(nums) ≤ 106

    • -109 ≤ nums[i] ≤ 109

    • Each item is at least as large as the item before it.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The keep rule reads the finished part. We can trust nums[write - 1] as the last value kept because the promise holds at every step.

    Swapping to keep what you skip

    What if the skipped items must stay in the list? Copying leaves junk behind. The keep_valid trace ended with [3, 5, 8, -2, 8]: the -1 was overwritten and the 8 appears twice. That is fine when only nums[:write] matters. Some problems want every item kept, with the skipped ones moved to the back.

    Swap instead of copy. When we keep nums[read], we swap it with nums[write]: the kept item goes forward, and whatever sat at write goes back to position read. Python swaps two slots in one line, nums[write], nums[read] = nums[read], nums[write]: it works out both values on the right first, then puts them in the two slots on the left. Before you step through, guess the final list for the same readings.

    Step throughKeep the good readings, and the error codes too
    Step 1 of 22
    Line 1 is about to run.
    def errors_to_back(nums):
    write = 0
    for read in range(len(nums)):
    if nums[read] >= 0:
    nums[write], nums[read] = nums[read], nums[write]
    write += 1
    return write
    Names
    no names yet
    Output
    (nothing printed yet)

    The gap between the pointers holds only skipped items. Every item from write up to read - 1 is one the walk passed and did not keep. So a swap always sends a skipped item back, never a good one. When nothing has been skipped yet, write equals read and the item swaps with itself.

    The kept items stay in order; the skipped ones may not. The -1 and -2 went in as -1, -2 and came out as -2, -1. When every skipped item is the same value, that cannot matter. Check the reordering on a new list.

    PredictWhere the skipped items land

    This is the swap version from the trace, on a new list. Type exactly what it prints: the list, a space, then write.

    nums = [-1, 4, -2, 6]
    write = 0
    for read in range(len(nums)):
        if nums[read] >= 0:
            nums[write], nums[read] = nums[read], nums[write]
            write += 1
    print(nums, write)
    

    Move zeroes is this walk with one change: the skipped items are the 0s.

    easyTwo pointers target 15 min

    Move zeroes to the end

    You get a list of integers nums. Rearrange it in place (inside the same list, using only a few extra variables) so that every 0 ends up at the end, and the other numbers stay in the order they had.

    The function returns nothing. The tests call it and then look at nums.

    Example 1
    Inputnums = [0, 4, 0, 9, 2]Outputnums becomes [4, 9, 2, 0, 0]

    4, 9 and 2 keep their order. The two 0s move to the end.

    Example 2
    Inputnums = [3, 8]Outputnums stays [3, 8]

    There are no 0s, so nothing moves.

    Example 3
    Inputnums = [0, 0, -1]Outputnums becomes [-1, 0, 0]

    -1 is not 0, so it moves to the front.

    Constraints
    • 0 ≤ len(nums) ≤ 106

    • -109 ≤ nums[i] ≤ 109

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Test != 0, not > 0. Negative numbers are not 0, and they must move forward too. The solution also shows a second way: copy the non-zero numbers forward as keep_valid did, then set every slot from write to the end to 0. The module's practice bank has one more in this family: Sort three colors (LeetCode 75), where three indexes grow three parts at once: the 0s at the front, the 2s at the back and the 1s between.

    So far: one walk, two ways to write. From problem to problem only the keep rule changes: not negative, not val, not None, a new value, not 0. Copy when the leftovers do not matter; swap when they must stay in the list.

    Merging from the back

    How do you merge two sorted lists when the room is inside one of them? nums1 = [4, 6, 0, 0] holds two real values, 4 and 6 (m = 2), and its last two slots are placeholders: room for the values of nums2 = [1, 5] (n = 2). The goal is nums1 = [1, 4, 5, 6].

    Merging from the front destroys values. To merge two sorted lists into a new, empty list, you keep a pointer at the front of each and copy the smaller value each step. Here there is no new list. The smallest value is 1, and it belongs in slot 0. But slot 0 holds the 4, which has not been placed yet. Writing the 1 there loses the 4.

    The free room is at the back, so fill from the back. The largest value of all is the larger of the two lists' last values, 6 and 5, and it belongs in the last slot, which is free. Three indexes do it: i reads nums1 from its last real value, j reads nums2 from its end, and write is the slot to fill, starting at the very end. Each step copies the larger waiting value to write, then moves that read pointer and write one step left. Before you step through, guess which list runs out first.

    Step throughMerging from the back
    Step 1 of 27
    Line 1 is about to run.
    def merge(nums1, m, nums2, n):
    i = m - 1
    j = n - 1
    write = m + n - 1
    while i >= 0 and j >= 0:
    if nums1[i] > nums2[j]:
    nums1[write] = nums1[i]
    i -= 1
    else:
    nums1[write] = nums2[j]
    j -= 1
    write -= 1
    while j >= 0:
    nums1[write] = nums2[j]
    j -= 1
    write -= 1
    Names
    no names yet
    Output
    (nothing printed yet)

    A write never lands on a waiting value, because write always equals i + j + 1. It starts that way (m − 1 plus n − 1 plus 1 is m + n − 1), and each step moves write and exactly one of i and j down by one. While nums2 has values left, j is at least 0, so write stays to the right of i.

    When nums1 runs out first, as here, the second loop copies the rest of nums2. If m is 0, nums1 has run out before the first step, and that loop copies all of nums2. There is no loop for the opposite case. Why not?

    Quick checkWhen nums2 runs out first

    The merge has a second loop for what is left of nums2, but none for what is left of nums1. Take nums1 = [1, 2, 9, 0] with m = 3, and nums2 = [5] with n = 1. The first loop places the 9 in slot 3, then the 5 in slot 2, and stops because j is -1. Why is it safe to stop there?

    Choose one answer, then check.

    If nums2 runs out first, stop. j is -1, so write equals i: every slot from 0 to i still holds its own nums1 value. Those are the smallest values of all, already sorted and already in their slots.

    Now write it. The free slots in nums1 are 0s, but a real 0 can be a value too: only m says where the real values end.

    easyTwo pointers target 15 min

    Merge two sorted lists in place

    You get two lists of integers, nums1 and nums2, and two counts, m and n. nums1 has length m + n. Its first m items are real values, sorted from smallest to largest. Its last n items are placeholder 0s that only reserve room. nums2 holds n values, also sorted from smallest to largest.

    Copy the values of nums2 into nums1 so that nums1 ends up holding all m + n values, sorted from smallest to largest. Work in place: write into nums1 itself and use only a few extra variables. A real value can also be 0, so only m tells you where the real values end.

    The function returns nothing. The tests call it and then look at nums1.

    Example 1
    Inputnums1 = [1, 4, 6, 0, 0], m = 3, nums2 = [2, 5], n = 2Outputnums1 becomes [1, 2, 4, 5, 6]

    The two 0s at the end were room for the 2 and the 5.

    Example 2
    Inputnums1 = [5, 6, 0, 0], m = 2, nums2 = [1, 2], n = 2Outputnums1 becomes [1, 2, 5, 6]

    Every value of nums2 is smaller, so both values of nums1 move to the back.

    Example 3
    Inputnums1 = [0, 0], m = 0, nums2 = [3, 8], n = 2Outputnums1 becomes [3, 8]

    nums1 has no real values yet: both 0s are room.

    Constraints
    • len(nums1) == m + n and len(nums2) == n

    • 0 ≤ m, n ≤ 104

    • -109 ≤ every value ≤ 109

    • nums1[:m] and nums2 are each sorted from smallest to largest.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The problem's reference solution folds the two loops into one. It loops while j >= 0 and takes from nums1 only when i >= 0 and nums1[i] > nums2[j]. Keep that i >= 0 check: in Python nums1[-1] is the last item, not an error, so without the check the loop would quietly compare against the wrong value.

    When to reach for read and write pointers

    How do you know a problem wants this walk? Reach for read and write pointers when a problem says "in place" and asks you to drop, keep or move items. Other signals: "return the new length", "move every 0 to the end", "merge into the first list". The walk is the same every time, and the work is three choices:

    1. The keep rule: which items belong in the finished part.
    2. Copy or swap: copy when the leftovers do not matter, swap when every item must stay in the list.
    3. Which end: start writing at the end where the free room is.

    Last, say the safety argument out loud. It is the question these problems invite.

    Say itSay it like you would in the room

    An interviewer asks: "You are writing into the same list you are reading. Why don't you lose data?" Answer for the read and write filter and for the merge from the back, in a few plain sentences, and finish with the cost.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Fixed-size windows