Two pointers and sliding windows
Two pointers summarize the part of an input that still matters. Their movement is useful only when you can explain why it discards no required answer. A sorted list supplies that argument for pair sums; a last-seen dictionary supplies it for a substring with distinct characters.
Read arrays and Python lists and hash maps before this lesson. The two examples below use invented inputs and keep the caller’s input unchanged.
Find a pair in a sorted list
Section titled “Find a pair in a sorted list”Given nondecreasing integer values and a target, return two distinct indices
whose values add to the target. Return None if no pair exists. The function
assumes the input is sorted; checking that assumption would itself require a
linear pass. Values and sums have constant arithmetic cost in this model.
Start at the two ends. If the sum is too small, no partner at or before right
can make the current left value work. Increase left. If the sum is too large,
no partner at or after left can make the current right value work. Decrease
right. The invariant is that any remaining solution lies between the pointers.
def sorted_pair( values: list[int], target: int) -> tuple[int, int] | None: """Find distinct positions with a requested sum in a sorted list.
Args: values: Integer values in nondecreasing order. target: Required pair sum.
Returns: A pair of indices, or None if no pair has the target sum. """ left = 0 right = len(values) - 1 while left < right: total = values[left] + values[right] if total == target: return left, right if total < target: left += 1 else: right -= 1 return None
values = [1, 3, 4, 6, 9]target = 13left, right = 0, len(values) - 1while left < right: total = values[left] + values[right] print("Indices", (left, right), "values", (values[left], values[right]), "sum", total) if total == target: break if total < target: left += 1 else: right -= 1print("Pair indices:", sorted_pair(values, target))Indices (0, 4) values (1, 9) sum 10Indices (1, 4) values (3, 9) sum 12Indices (2, 4) values (4, 9) sum 13Pair indices: (2, 4)Each iteration moves a pointer or returns. Their initial separation is at most
n - 1, so the time is O(n) and auxiliary space is O(1). Sorting an unsorted
input first would add O(n log n) time and could lose the original positions.
For original indices in an unsorted list, a dictionary is often a better choice.
Keep a window without repeated characters
Section titled “Keep a window without repeated characters”Return the start and exclusive end of the longest substring with no repeated
character. If several spans tie, return the earliest one. An empty string
returns (0, 0). Python string elements are Unicode code points; a displayed
character can contain more than one code point.
The window is text[left:right + 1]. Before a new character enters, every
character in the window is distinct. If its previous occurrence lies inside
the window, move left just past that occurrence. Otherwise keep left where
it is. The boundary must never move backward.
def longest_unique_span(text: str) -> tuple[int, int]: """Find the earliest longest span of distinct Unicode code points.
Args: text: String to inspect.
Returns: Start and exclusive end indices of the selected span. """ last_seen: dict[str, int] = {} left = 0 best_start = 0 best_end = 0 for right, character in enumerate(text): previous = last_seen.get(character, -1) left = max(left, previous + 1) last_seen[character] = right if right + 1 - left > best_end - best_start: best_start, best_end = left, right + 1 return best_start, best_end
text = "abcaefb"last_seen: dict[str, int] = {}left = 0for right, character in enumerate(text): previous = last_seen.get(character, -1) left = max(left, previous + 1) last_seen[character] = right print("Read", character, "bounds", (left, right + 1), "window", text[left:right + 1])start, end = longest_unique_span(text)print("Selected span:", (start, end))print("Selected substring:", text[start:end])print("Length:", end - start)Read a bounds (0, 1) window aRead b bounds (0, 2) window abRead c bounds (0, 3) window abcRead a bounds (1, 4) window bcaRead e bounds (1, 5) window bcaeRead f bounds (1, 6) window bcaefRead b bounds (2, 7) window caefbSelected span: (1, 6)Selected substring: bcaefLength: 5The dictionary keeps the most recent position of each character in the processed prefix. Moving past the new character’s earlier occurrence removes its only possible duplicate in the current window. Any earlier left boundary would keep that duplicate. The algorithm therefore considers the longest valid window for every right endpoint.
The function performs one pass with expected O(1) dictionary operations, so
expected time is O(n). Its auxiliary space is O(min(n, a)), where a is the
number of possible characters. Its returned pair occupies O(1) space.
Extracting the final substring costs O(k) time and output space for length k.
The trace prints a slice at every step. Those diagnostic slices can cost
O(n²) total time and output characters; they are not part of the function’s
linear-time implementation. Python dictionary collision behavior can also
worsen the function’s expected time bound.
Test pointer movement
Section titled “Test pointer movement”An old occurrence before left must not move left backward. The string
abba exposes that error. The list [5] exposes an implementation that uses
the same element twice for a pair.
assert sorted_pair([], 4) is Noneassert sorted_pair([5], 10) is Noneassert sorted_pair([5, 5], 10) == (0, 1)assert sorted_pair([-5, -1, 2, 8], 3) == (0, 3)assert sorted_pair([1, 2, 3], 20) is Noneassert longest_unique_span("") == (0, 0)assert longest_unique_span("abba") == (0, 2)assert longest_unique_span("aaaa") == (0, 1)assert longest_unique_span("abcd") == (0, 4)print("The pair and window boundary cases pass.")The pair and window boundary cases pass.Practice
Section titled “Practice”Two Sum II tests the sorted-pair invariant. Read the required index convention before you return your answer.
Longest Substring Without Repeating Characters
tests the window invariant. Explain why the previous occurrence of a character
can be irrelevant once it lies before left.
Download the Python source to run the complete example locally.
Further reading
Section titled “Further reading”Python’s sequence operations define index and slice boundaries. They help keep the exclusive end of the returned span separate from the current character’s index.
Python’s dictionary documentation
describes key lookup and get. These operations maintain the most recent
character position without a second scan of the window.