Dashboard/Coding patterns/01. Two Pointers

CODING PATTERNS · LESSON 1 OF 28 · 100 MIN VIDEO · 34 PROBLEMS · ★ FREE SAMPLE VIDEO

Two Pointers

Module Progress (0 / 34 Problems Solved)0%
Coding patterns Track (0 / 28 Modules) · Overall 0/80 (0%)0%
Narrated HD Video Lesson · 100 min · 35 YouTube-style timestamped chapters
0:00 / 1:39:04
VIDEO TIMESTAMPS · 35 CHAPTERSNow at 0:00 — Intro & Pattern Mental Model
PATTERN STUDY GUIDE

Two Pointers — How the Pattern Works

The Two Pointers pattern coordinates two (or occasionally three) index or node references across one or two linear structures according to a deterministic movement rule. At every iteration, a structural invariant — such as sorted monotonicity, mirror symmetry, a fixed pointer gap, or a read/write partition boundary — guarantees that advancing a pointer permanently discards candidate states that cannot form a valid or optimal solution. This state-space pruning collapses nested O(n^2) brute-force searches or multi-pass copies into a single O(n) scan (or O(n log n) when sorting first) while typically requiring only O(1) auxiliary space.

WHEN TO USE THIS PATTERN
  • Pair, triplet, or pair-counting problems on a sorted (or sortable) array where shifting left or right endpoints monotonically increases or decreases a sum.
  • Palindrome checks, 180-degree digit rotations, or sequence/substring reversals that compare or swap mirrored indices (i, n - 1 - i) from both ends inward.
  • In-place array filtering, deduplication, run-length compression, or 3-way partitioning where a write pointer trails a read scanner without allocating a copy.
  • Single-pass linked list or parent-pointer tree problems requiring a fixed k-node offset from the tail or path-length equalization via head switching.
  • Synchronized traversal across two strings or sorted arrays — including subsequence matching, alternating or monotonic merges, word abbreviations, and chunked version comparisons.
COMMON INTERVIEW PITFALLS
  • Off-by-one loop termination (left < right vs. left <= right): pair searches require two distinct indices (left < right), whereas self-symmetric center validation (Strobogrammatic Number) or unclassified middle regions (Sort Colors with mid <= high) must evaluate the meeting index.
  • Advancing mid after swapping with high in 3-way partitioning (Sort Colors): the value swapped in from nums[high] has not been inspected yet, so only high should decrement on that branch.
  • Testing value equality (!=) instead of object identity (is not) on linked list or tree nodes (Intersection of Two Linked Lists, Lowest Common Ancestor III), which terminates prematurely on distinct nodes sharing duplicate values.
  • Violating sorted or non-overtaking invariants: read/write deduplication misses non-adjacent duplicates if the input is unsorted, and in-place string encoding is safe only when encoded output never exceeds the consumed input length.
Opposite-End Converging PointersPair-sum search on a sorted array, in-place reversal, or palindrome and mirror symmetry checks.
def two_pointer_converge(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        curr = nums[left] + nums[right]
        if curr == target:
            return [left, right]
        if curr < target:
            left += 1
        else:
            right -= 1
    return [-1, -1]
Same-Direction Read / Write PointersIn-place array compaction, element removal, deduplication, or stable partitioning without extra memory.
def compact_in_place(nums, should_keep):
    write = 0
    for read in range(len(nums)):
        if should_keep(nums[read], write, nums):
            nums[write] = nums[read]
            write += 1
    return write
Dual-Sequence Parallel PointersAdvancing through two strings or sorted arrays at independent paces for subsequence matching, merging, or chunk parsing.
def walk_two_sequences(seq1, seq2):
    i = j = 0
    while i < len(seq1) and j < len(seq2):
        if seq1[i] == seq2[j]:
            i += 1
            j += 1
        else:
            j += 1
    return i == len(seq1)
Path-Equalizing Linked PointersFinding the intersection of two singly linked lists or the lowest common ancestor with parent pointers in O(1) space.
def equalize_paths(head_a, head_b):
    a, b = head_a, head_b
    while a is not b:
        a = a.next if a else head_b
        b = b.next if b else head_a
    return a

28. Merge Strings Alternately

Optimal Target: O(n + m) time · O(n + m) space

Given two strings word1 and word2, merge them by alternating characters starting with word1. If one string is longer than the other, append the remaining suffix of the longer string to the end, and return the merged string.

EXAMPLE 1
Input: word1 = "abc", word2 = "pqrs"
Output: "apbqcrs"
Explanation: Alternating pairs produce 'a','p', 'b','q', 'c','r', and appending the leftover suffix word2[3:] = "s" gives "apbqcrs".
VISUAL INPUT
abc
pqrs
AUTOMATED TEST SUITE
Test Case 1
Input: "abc", "pqrs"
Expected: "apbqcrs"
Test Case 2
Input: "abcd", "pq"
Expected: "apbqcd"
Test Case 3
Input: "", "x"
Expected: "x"
Python 3.14 Runtime Ready

Click ▶ Run Tests (or press ⌘+Enter) to execute merge_alternately against all 3 test cases in WebAssembly Python.

Pattern Checkpoint Quizzes

CHECKPOINT QUIZ #1

On a sorted array, left plus right comes out too big. Which pointer should move?

CHECKPOINT QUIZ #2

Same list, one to five, but now n is three. Where does left stop, once right is on the last node?

CHECKPOINT QUIZ #3

Back in calendar, pointer j reads the digit three. What moves?

CHECKPOINT QUIZ #4

What's the next permutation of one, three, two? That's the next arrangement up, in dictionary order.

CHECKPOINT QUIZ #5

Take five, one, five, with bounds one and five. How many subarrays have smallest one and largest five?

CHECKPOINT QUIZ #6

Suppose the sorted array has no negative numbers at all. What's the fastest way to get the sorted squares?

CHECKPOINT QUIZ #7

You reverse a word of seven letters with two pointers, just like in problem eighteen. How many swaps does it take?

CHECKPOINT QUIZ #8

Using the same three steps, what's the next ordering after one, five, four, three?

CHECKPOINT QUIZ #9

Feed the remove duplicates code from problem twenty-five the array one, two, one. That's not sorted. What happens?

CHECKPOINT QUIZ #10

Compare one dot zero one with one dot zero zero one. What does the function return?

CHECKPOINT QUIZ #11

One string is a, hash, hash, c. The other is hash, a, hash, c. Do they type the same text?