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

Lesson 1 of 4

Two pointers from both ends

Put one index at each end of a list or string and walk them toward each other. Every step proves that one item cannot be part of a better answer, so problems that seem to need every pair take one pass.

About 2 hours, with the 4 problems worked in it
By the end you can
  • Trace two pointers moving inward and say where they stop on odd and even lengths

  • Check a palindrome by comparing mirror pairs and skipping characters that do not count

  • Solve two sum on a sorted list in O(n) time and O(1) extra space, and say why each pointer move is safe

  • Find the two walls that hold the most water by always moving the shorter wall

  • Solve three sum by sorting, fixing one number, and skipping repeated values

Does "reader" read the same backwards? You would not copy it out in reverse. You would put one finger on the first letter and one on the last, check that they match, and slide both fingers one letter toward the middle. Then again, until the fingers meet or a pair disagrees. Two fingers closing in from the ends is the whole pattern of this lesson.

The same two fingers solve harder problems. On a sorted list of prices, they find two prices that add up to a gift card's value. On a row of walls, they find the two walls that hold the most water. Each of these seems to need every pair, which is O(n2) work, and each one takes a single walk inward, O(n). (O(n) means the work grows in step with the length n; O(n2) means it grows like n times n.)

What makes it work is one question, asked at every step: which finger can move without losing the answer? Each section below answers it for one problem.

Two fingers on a word

How do you compare a word with its reverse without building the reversed copy? Compare mirror pairs: the first character with the last, the second with the second to last, and so on. Each comparison needs two positions, so we keep two indexes. An index that we move along the data is called a pointer. left starts at position 0 and right at the last position, len(word) - 1. (Positions count from 0, so a five-letter word has positions 0 to 4.)

The trace runs the check on two words: "radar", a palindrome (a word that reads the same both ways), and "reader", which is not. The two arrows under the word are the pointers. Before you step through, guess how many pairs each call compares.

Step throughComparing mirror pairs from both ends
Step 1 of 30
Line 1 is about to run.
def is_mirror(word):
left = 0
right = len(word) - 1
while left < right:
if word[left] != word[right]:
return False
left += 1
right -= 1
return True
print(is_mirror("radar"), is_mirror("reader"))
Names
no names yet
Output
(nothing printed yet)

The loop runs while left < right, that is, while the pointers sit on two different positions. On an odd length they meet on the middle character, which is its own mirror and needs no check. On an even length they step past each other. Either way, when no pair disagrees, every mirror pair is compared exactly once. A mismatch ends the walk at once, because one disagreeing pair is enough to say no.

PredictWhere the pointers stop

This loop moves the pointers exactly as is_mirror does when every pair matches, but compares nothing. Type exactly what it prints, one line per word.

for word in ["kayak", "noon"]:
    left = 0
    right = len(word) - 1
    while left < right:
        left += 1
        right -= 1
    print(word, left, right)

The same walk can write instead of compare. Swap each mirror pair, and the list ends up reversed in place: the list itself changes, and no copy is made. Python swaps two values with a, b = b, a, which works because the right side is built from the old values before either name changes.

Put in orderReverse a list in place

Put the lines in order to build reverse_in_place(items), which reverses items by changing the list itself and returns nothing. It is the mirror walk, with a swap where the comparison was. Indentation is 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)
    • left, right = left + 1, right - 1
    • left, right = 0, len(items) - 1
    • def reverse_in_place(items):
    • while left < right:
    • left, right = right, left
    • items[left], items[right] = items[right], items[left]
    • items[left] = items[right]

    Now a real problem. Real text has spaces, commas and capital letters, and the problem says those do not count: "No, on" is a palindrome because its letters, in lowercase, are noon. Two string methods from module 1 do the work for one character c: c.isalnum() is True when c is a letter or a digit, and c.lower() gives the lowercase version.

    Each pass of the loop now makes one decision. Call the text s. If s[left] does not count, move left past it. Otherwise, if s[right] does not count, move right past it. Otherwise compare the two characters in lowercase. A skip moves one pointer; a match moves both, because a skipped character sits on one side only, while a matched pair has one character on each side.

    easyTwo pointers target 15 min

    Valid palindrome

    A palindrome reads the same from left to right as from right to left, like "noon". You get a string s. Keep only its letters and digits, and treat uppercase and lowercase as the same letter. Return True if what is left is a palindrome, and False if it is not.

    Spaces, punctuation and other symbols do not count, so "No, on" is a palindrome: its letters, in lowercase, are noon. Digits do count, and a digit never matches a letter. A string with no letters or digits at all is a palindrome too, because nothing is left to disagree.

    Example 1
    Inputs = "Top spot"OutputTrue

    Keeping letters and digits in lowercase leaves topspot, which reads the same both ways.

    Example 2
    Inputs = "Top spots"OutputFalse

    topspots backwards is stopspot. The first and last letters already differ: t and s.

    Example 3
    Inputs = ", ."OutputTrue

    No letters or digits are left, and an empty string reads the same both ways.

    Constraints
    • 0 ≤ len(s) ≤ 2 × 105

    • s holds printable ASCII characters: letters, digits, spaces, punctuation and symbols such as $ or @.

    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 pointers never build a cleaned copy. Cleaning the string and reversing it is also O(n) time, but it builds two new copies of up to n characters each, the cleaned text and its reverse; the pointers store two integers. The trap is isalpha(), which is True only for letters: it would skip digits and call "a1a2" a palindrome.

    So far: two pointers start at the two ends and move inward while left < right. Every pass moves at least one pointer one place closer to the other, so the walk is O(n).

    Sorted two sum: which pointer moves

    In the mirror walk both pointers moved together. Here only one pointer moves per step, and the sum decides which. You have a list of prices sorted from cheapest to most expensive, and a gift card worth 10. Which two prices add up to exactly 10?

    The brute force (the plain method that tries everything) checks every pair of positions: O(n2). Module 3's two sum did better with a dict: for each number x, look up its partner target - x among the numbers already passed. That is O(n) time but O(n) extra space, and it ignores what this list gives us: it is sorted.

    Put left on the cheapest price and right on the most expensive, and add the two. The prices from left to right are the ones still in play: not yet ruled out.

    • Too small: nums[right] is the biggest price still in play, and even it is not enough for nums[left]. Every other partner is the same or smaller. So nums[left] is in no answer: move left up one.
    • Too big: by the mirror argument, nums[left] is the smallest price still in play, and even it overshoots with nums[right]. So nums[right] is in no answer: move right down one.
    • Equal: done.

    A pointer only moves past a number we have proved cannot be in the answer. That is why each move is safe: a sum that is too small drops the smaller number, and a sum that is too big drops the bigger one. Before you step through, guess the two prices in [1, 3, 4, 6, 8, 11] that use a card worth 10, and how many sums the walk computes to find them.

    Step throughTwo prices that add up to the card
    Step 1 of 29
    Line 1 is about to run.
    def pick_two(nums, target):
    left = 0
    right = len(nums) - 1
    while left < right:
    total = nums[left] + nums[right]
    if total == target:
    return [nums[left], nums[right]]
    if total < target:
    left += 1
    else:
    right -= 1
    return None
    Names
    no names yet
    Output
    (nothing printed yet)

    Each sum either finds the pair or rules out one number for good. Six numbers start five places apart, so the walk computes at most five sums; this one needed all five. Compare that with the brute force:

    Work it outHow many pairs?

    The brute force for this question tries every pair of different positions. How many pairs does a list of 6 numbers have? (Count each pair once: positions 0 and 1 are the same pair as 1 and 0.)

    pairs

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

    Check the rule on a new list before you write it.

    Quick checkWhich pointer moves?

    nums = [2, 4, 7, 9, 13], target = 17. The pointers start at the ends: nums[0] + nums[4] is 2 + 13 = 15, below the target. What should happen next?

    Choose one answer, then check.

    The problem asks for the two positions instead of the two prices, and promises that exactly one pair exists. The walk is the same; only the return changes, to [left, right].

    mediumTwo pointers target 25 min

    Two sum in a sorted list

    You get a list of integers nums, sorted from smallest to largest, and an integer target. Exactly one pair of different positions holds two numbers that add up to target. Return those two positions as a list [i, j] with i < j.

    Aim for O(1) extra space: the sorted order is enough, so you need no dict or set. Positions count from 0, as Python indexes do (LeetCode's version counts them from 1).

    Example 1
    Inputnums = [1, 4, 5, 7, 12], target = 9Output[1, 2]

    nums[1] + nums[2] is 4 + 5 = 9. No other pair makes 9.

    Example 2
    Inputnums = [-4, -1, 0, 3, 10], target = 6Output[0, 4]

    -4 + 10 = 6: the pair can be the two ends.

    Example 3
    Inputnums = [5, 5, 8], target = 10Output[0, 1]

    Equal values at two different positions are a valid pair.

    Constraints
    • 2 ≤ len(nums) ≤ 3 × 104

    • -109 ≤ nums[i], target ≤ 109

    • nums is sorted from smallest to largest; equal neighbors are allowed.

    • Exactly one valid pair exists.

    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.

    Interviewers like to change a known problem to see whether you understand the argument or only remember the code. Here is such a change: count the pairs whose sum is below the target. A too-small sum now settles more than one pair at once.

    Code itCount the pairs below the target

    Write count_below(nums, target). nums is sorted from smallest to largest. Return how many pairs of different positions i < j have nums[i] + nums[j] < target. For [1, 2, 4, 5, 8] and target 7 the answer is 4: 1 + 2, 1 + 4, 1 + 5 and 2 + 4.

    Use one walk from both ends. The tests include a list of 15,000 numbers, where trying every pair is too slow.

    ⌘+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.

    So far: in a sorted list, the sum of the two ends says which end is useless. Too small drops the left number; too big drops the right one. Each sum settles every pair that uses the dropped number, which is how one walk replaces the n(n − 1)/2 checks of the brute force.

    Container with most water: move the shorter wall

    Now we measure something other than a sum. A row of walls stands on flat ground, one unit apart. Pick two, and water fills the space between them up to the shorter wall, because above that it spills over. The amount is the width times the shorter height: (right - left) * min(heights[left], heights[right]). The walls between the two you pick do not count: ignore them. Which two walls hold the most?

    Start with the widest pair, the two ends, and measure it. Now one wall has to go, and the question is which one can go without losing a better answer. Say the left wall is the shorter. Pair it with any other wall between the pointers: the width shrinks, and the water can never rise above the left wall, because the shorter wall sets the level. So every pair the left wall could still make holds no more than the pair we measured. It has nothing left to offer. Always move the pointer at the shorter wall.

    The taller wall has no such cap: it might pair with a tall wall further in. Before you step through, guess which two of the walls [2, 7, 3, 8, 4, 5] hold the most.

    Step throughMoving the shorter wall
    Step 1 of 33
    Line 1 is about to run.
    def max_water(heights):
    left = 0
    right = len(heights) - 1
    best = 0
    while left < right:
    water = (right - left) * min(heights[left], heights[right])
    best = max(best, water)
    if heights[left] < heights[right]:
    left += 1
    else:
    right -= 1
    return best
    Names
    no names yet
    Output
    (nothing printed yet)

    Now do one by hand, one table row per measurement.

    On paperMeasure the walls by hand

    Run the shorter-wall walk on paper for heights = [3, 9, 4, 8, 2]. Make a table with the columns left, right, width, shorter wall, water and best, one row per measurement, and write which pointer moves after each row. What is best 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.

    best

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

    Now the full problem. Its examples use new walls; the walk is the one you did by hand.

    mediumTwo pointers target 25 min

    Container with the most water

    A row of vertical walls stands on flat ground, one unit apart. heights[i] is the height of the wall at position i. Pick any two walls. Water poured between them rises to the top of the shorter wall and no higher, because above that it spills over. So the amount of water held by the walls at positions i < j is

    (j - i) * min(heights[i], heights[j])

    The walls between the two you pick do not matter: ignore them. Return the largest amount of water that any two walls can hold.

    Example 1
    Inputheights = [2, 5, 4, 1, 6, 3]Output15

    The walls at positions 1 and 4 (heights 5 and 6) are 3 apart. The shorter is 5, so they hold 3 × 5 = 15.

    Example 2
    Inputheights = [3, 1, 2, 4]Output9

    The two ends are 3 apart and the shorter is 3: 3 × 3 = 9.

    Example 3
    Inputheights = [7, 7]Output7

    Two walls 1 apart, both 7 tall: 1 × 7 = 7.

    Constraints
    • 2 ≤ len(heights) ≤ 105

    • 0 ≤ heights[i] ≤ 104

    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.

    Ties do not need a rule of their own. When both walls have the same height, each one is "the shorter wall", so the argument lets either go; the solution moves right. best starts at 0, which is the right answer when every wall has height 0.

    So far: each step measures one pair, then drops the one wall that has nothing better to offer. The sorted two sum walk drops a number that cannot reach the target; this walk drops a wall that cannot beat best. Same shape, different proof.

    Three sum: fix one number, then two pointers

    Three sum asks for every triple (a group of three values, from three different positions) that adds up to 0, with each triple listed once. Three nested loops try every triple of positions: about 166 million of them for 1,000 numbers. That is O(n3): the work grows like n times n times n.

    Fix one number, and the rest is two sum. If the smallest number of the triple is nums[i], the other two must add up to -nums[i]. Sort the list first, and that is sorted two sum on the positions after i: left = i + 1, right at the last position, and the same moves, now testing whether the total of all three is below or above 0. range(len(nums) - 2) stops i while two positions remain after it, one for left and one for right.

    Two things change from sorted two sum. One i can have several triples, so a match records the triple, moves both pointers, and keeps walking. Moving both is safe: any other partner for nums[left] would have to equal nums[right], which gives the same triple again, and the same holds for nums[right]. And each triple must appear once, even when values repeat. Sorting puts equal values next to each other, so a repeat always sits beside another copy, and two skips handle it:

    • Skip a repeated smallest number. If nums[i] == nums[i - 1], the pass for the first copy of this value already searched every position after i, and more. So this pass could only find triples already recorded, and continue moves on to the next i.
    • Skip a repeated middle number after a match. Move left past every copy of the value that matched.

    The trace runs on [2, -2, 0, 2, -2, 0], which holds two copies of each value. Guess first: how many triples does it record?

    Step throughThree sum with both skips
    Step 1 of 47
    Line 1 is about to run.
    def three_sum(nums):
    nums = sorted(nums)
    triples = []
    for i in range(len(nums) - 2):
    if i > 0 and nums[i] == nums[i - 1]:
    continue
    left = i + 1
    right = len(nums) - 1
    while left < right:
    total = nums[i] + nums[left] + nums[right]
    if total < 0:
    left += 1
    elif total > 0:
    right -= 1
    else:
    triples.append([nums[i], nums[left], nums[right]])
    left += 1
    right -= 1
    while left < right and nums[left] == nums[left - 1]:
    left += 1
    return triples
    Names
    no names yet
    Output
    (nothing printed yet)
    PredictWhich passes run?

    This is the outer loop of three sum on a sorted list, with the two-pointer walk left out. Type exactly what it prints.

    nums = [-3, -3, -1, -1, -1, 2]
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        print(i, nums[i])
    

    Now write it yourself. The problem's examples add a case the trace did not have: one triple that uses two copies of the same value.

    mediumTwo pointersSorting target 25 min

    Three sum

    You get a list of integers nums. A triple here is three numbers taken from three different positions of nums. Return every triple whose three numbers add up to 0, as a list of lists of three numbers.

    A triple is known by its values, not by its positions. [-1, 0, 1] and [0, 1, -1] are the same triple, and so are two triples that use different copies of a repeated value. List each triple once. The triples can come in any order, and so can the three numbers inside each one. If no triple adds up to 0, return an empty list.

    Example 1
    Inputnums = [-2, 0, 1, 1, 2]Output[[-2, 0, 2], [-2, 1, 1]]

    -2 + 0 + 2 = 0 and -2 + 1 + 1 = 0. The two 1s sit at different positions, so one triple can use both.

    Example 2
    Inputnums = [2, -3, 1, -3, 0, 1]Output[[-3, 1, 2]]

    Two -3s and two 1s give four ways to pick positions for -3 + 1 + 2, but it is one triple of values, listed once.

    Example 3
    Inputnums = [4, -1, 5]Output[]

    The only triple adds up to 8.

    Constraints
    • 0 ≤ len(nums) ≤ 3,000

    • -105 ≤ nums[i] ≤ 105

    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.

    right needs no skip of its own. Once left holds a bigger value, the old right value makes the total too big, and the normal rule moves right. And with fewer than three numbers, range(len(nums) - 2) is empty, so the answer is [].

    The pattern, and when to reach for it

    All four walks share one frame. What changes from problem to problem is the proof that lets a pointer move.

    Reach for this pattern when the input is sorted, or sorting is cheap next to the rest of the work, and the question is about pairs. Sorting costs O(n log n), so it adds nothing to the Big O of an O(n2) answer like three sum. Some walks need no sorting at all: mirror questions (palindromes, reversing) get their proof from the mirror, and the container gets it from the shorter wall. If the list is not sorted and you need the original positions, the two sum dict is usually the better tool.

    The module's practice bank has one more in this family: Squares of a sorted list, where the biggest square always comes from one of the two ends.

    Last, say it the way you would in the room.

    Say itWhy the shorter wall?

    An interviewer gives you container with most water. Explain your plan as you would say it before typing: the brute force and its cost, then the walk, the notebook, the promise and the cost of the two-pointer version. Include why it is safe to move the shorter wall.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Read and write pointers