Skip to content
CodeItRaw
Two Pointers & Sliding Window

Lesson 2/4

One pointer goes at the start of the list and one at the end, and they walk toward each other. Only one moves at each step; you decide which by looking at where things stand.

lo, hi = 0, len(values) - 1
while lo < hi:
total = values[lo] + values[hi]
if total == key:
return True
if total < key:
lo += 1
else:
hi -= 1
return False
Because the list is sorted: if the sum is too small, the only way to make it bigger is to move the left one right; if too big, the right one left. Each step rules one element out for good, so it ends in n steps.

A palindrome check is the same walk: are the elements at the two ends equal, and if so both step in. When they meet in the middle, it is done.

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

    Palindrome Check

    Code reading · Bug Hunt

  2. 02

    Pair in Sorted

    Function

  3. 03

    Sum Lock

    Code Duel

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