Skip to content
CodeItRaw
Two Pointers & Sliding Window

Lesson 3/4

Two pointers do not have to be in the same list. Merging two sorted lists, you hold a pointer in each; at every step you take the smaller one and move only that list's pointer on.

i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
return out + a[i:] + b[j:]
The loop stops when one list runs out; what is left in the other is already sorted and goes on the end as it is. The number of steps is the two lengths added together.

This is the heart of merge sort, which you will meet later. What to see for now: two pointers, one moves at each step, neither ever goes back.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Merging Two Lists

    Code reading · Predict the Output

  2. 02

    Sorted Pair Sum

    Code reading · Read the Big-O

If you would rather not wait for the order, every problem is open without locks: Problem list