Common String Patterns & Problem-Solving Techniques
Two-Pointer Intuition on Strings
Read aloud is unavailable in this browser.
Beyond Single-Index Thinking
When you first learn to traverse a string, you use a single index—moving from left to right (or right to left), examining one character at a time. This is fundamental, but it's also limiting. Many string problems require reasoning about two positions simultaneously: comparing characters at opposite ends, tracking a range of interest, or processing pairs of elements.
The two-pointer technique addresses these problems by maintaining two position markers that move through the string according to problem-specific rules. This simple idea—two indices instead of one—unlocks efficient solutions to a surprisingly large class of problems.
This page builds your intuition for two-pointer thinking on strings. We won't implement specific algorithms here; instead, we'll develop the mental model that lets you recognize when two pointers apply and how to reason about their movement.
By the end of this page, you will understand the core insight behind two-pointer techniques, distinguish between converging and co-moving pointer patterns, recognize problem characteristics that signal two-pointer applicability, and gain intuition for how pointers move based on problem conditions.
The Core Insight
At its heart, the two-pointer technique exploits a simple observation:
If examining all pairs of positions naively would take O(n²) time, then perhaps we can use problem structure to avoid examining most pairs.
Consider a string of length n. There are n × n = n² pairs of positions (i, j). A naive approach examining all pairs is quadratic. But often, the problem has structure that lets us:
- Start with a carefully chosen initial pair
- Move one or both pointers based on what we observe
- Visit only O(n) pairs total while still finding the answer
This reduction from O(n²) to O(n) is the power of two-pointer techniques.
Two-pointer techniques work by elimination. Each pointer movement eliminates a large set of pairs from consideration. When a pointer moves right, it says 'No pair with that old position is interesting anymore.' This bulk elimination is what achieves linear time.
Why Two Pointers, Not Three or Four?
Two pointers are sufficient for problems involving:
- Pairs of characters (palindrome checking, two-sum-like queries)
- Ranges defined by start and end (substrings, windows)
- Relative positions (leader/follower, fast/slow)
More complex problems sometimes use three pointers (Dutch national flag) or more, but two covers the vast majority of linear-structure problems.
Not Magic—Problem Structure Required
Two-pointer techniques aren't universally applicable. They work when the problem has monotonicity or ordering that lets us make progress with each move. If no such structure exists, two pointers won't help—you genuinely need to check all pairs.
The Two Fundamental Patterns
Two-pointer techniques on strings fall into two main patterns, each with a distinct mental model.
Pattern 1: Opposite-Direction (Converging) Pointers
Two pointers start at opposite ends and move toward each other.
Initially: L → ← R
[ a ] [ b ] [ c ] [ d ] [ e ]
0 1 2 3 4
After moves: ... → L R ← ...
[ a ] [ b ] [ c ] [ d ] [ e ]
0 1 2 3 4
Use when: You need to compare/process from both ends, or when the answer involves opposite ends meeting in the middle.
Examples:
- Palindrome checking (compare first and last, move inward)
- Reversing a string in place
- Two-sum in sorted array (adjust sum by moving appropriate pointer)
- Container with most water (area determined by two sides)
Pattern 2: Same-Direction (Co-Moving) Pointers
Both pointers start at or near the same position and move in the same direction, though at different speeds or conditions.
Initially: S, F →
[ a ] [ b ] [ c ] [ d ] [ e ]
0 1 2 3 4
After moves: S → F →
[ a ] [ b ] [ c ] [ d ] [ e ]
0 1 2 3 4
Use when: You need to track a range (window) or distinguish between two regions of the array.
Examples:
- Slow/Fast pointers for cycle detection (not typically on strings, but same idea)
- Maintaining a window (covered in next page on sliding window)
- Removing duplicates in place
- Partitioning elements
Start: left = 0, right = n-1. Movement: Pointers approach each other. Termination: left >= right (they meet or cross). Classic use: Palindrome checking, two-sum in sorted array.
Start: Both at or near position 0. Movement: Both move right, but at different rates. Termination: Fast pointer reaches end. Classic use: Window-based problems, in-place modifications.
Converging Pointers: Deep Dive
Let's develop deep intuition for converging pointers through the classic application: palindrome checking.
The Problem: Determine if a string reads the same forwards and backwards.
The Naive Approach:
- Create the reversed string
- Compare to original
- Time: O(n), Space: O(n)
The Two-Pointer Approach:
- Compare first character with last, second with second-to-last, etc.
- If all pairs match, it's a palindrome
- Time: O(n), Space: O(1)
12345678910111213141516171819202122
IsPalindrome(S): left = 0 right = length(S) - 1 WHILE left < right: IF S[left] ≠ S[right]: RETURN false // Mismatch found left += 1 // Move inward right -= 1 // Move inward RETURN true // All pairs matched // Trace for "racecar" (length 7):// // Step | left | right | S[left] | S[right] | Match?// -----|------|-------|---------|----------|-------// 0 | 0 | 6 | 'r' | 'r' | Yes// 1 | 1 | 5 | 'a' | 'a' | Yes// 2 | 2 | 4 | 'c' | 'c' | Yes// 3 | 3 | 3 | (left >= right, stop)// // Result: true (palindrome)Why This Works:
A palindrome has the property: S[i] = S[n-1-i] for all valid i. The two pointers check exactly these symmetric pairs. Once left crosses right, we've verified all necessary pairs.
The Insight About Pairs Examined:
We examine at most n/2 pairs (each iteration compares one pair and moves both pointers). This is O(n) time, but we never explicitly enumerate all n² pairs—the structure of the problem tells us exactly which pairs matter.
Variations:
- Skip non-alphanumeric characters (for "A man, a plan, a canal: Panama")
- Case-insensitive comparison
- Allow one mismatch (Valid Palindrome II problem)
The palindrome structure (symmetric around center) directly maps to converging pointers. Anytime you see end-to-end symmetry or need to compare extremes, think converging pointers. Other examples: checking if a string can be made into a palindrome by removing at most one character, finding the longest palindromic prefix.
Co-Moving Pointers: Deep Dive
Co-moving pointers (also called slow/fast or read/write pointers) are essential for in-place string modifications and range tracking.
Canonical Example: Removing Duplicates
Given a sorted string, remove duplicate characters in place.
The Mental Model:
- Slow pointer (write): Marks the position where next unique character should be written
- Fast pointer (read): Scans ahead to find the next unique character
The intuition: slow pointer represents "the cleaned portion," fast pointer represents "exploration into unseen territory."
12345678910111213141516171819202122232425
RemoveDuplicates(S): IF length(S) <= 1: RETURN S // Nothing to remove write = 1 // Slow pointer: where to write next unique FOR read = 1 TO length(S) - 1: // Fast pointer scans IF S[read] ≠ S[write - 1]: // New unique character? S[write] = S[read] // Write it write += 1 // Advance write position RETURN S[0:write] // Result is everything up to write // Trace for "aabbccc":// // Step | read | write | S[read] | S[write-1] | Action// -----|------|-------|---------|------------|-------// 0 | 1 | 1 | 'a' | 'a' | Skip (duplicate)// 1 | 2 | 1 | 'b' | 'a' | Write 'b' at 1, write→2// 2 | 3 | 2 | 'b' | 'b' | Skip (duplicate)// 3 | 4 | 2 | 'c' | 'b' | Write 'c' at 2, write→3// 4 | 5 | 3 | 'c' | 'c' | Skip (duplicate)// 5 | 6 | 3 | 'c' | 'c' | Skip (duplicate)// // Result: S[0:3] = "abc"Key Observations:
-
Write pointer is always ≤ read pointer: We can overwrite positions we've already read.
-
No extra space needed: We're modifying in place, achieving O(1) space.
-
Single pass: Both pointers move left to right, total O(n) time.
-
Invariant maintained: Everything before write pointer is the final result so far.
Why "Fast" and "Slow"?
In this example, both pointers move, but fast moves every iteration while slow moves only sometimes. Over time, fast "outruns" slow, creating a gap. This gap represents duplicates that were skipped.
Think of it as copying a string with a filter. The 'read' pointer scans the source. The 'write' pointer builds the result. The filter condition (e.g., 'is this character unique?') decides whether to copy. This model applies to many in-place filtering problems.
Pointer Movement Strategies
The key to two-pointer success is knowing when and how to move each pointer. Here are the main strategies:
Strategy 1: Alternating Movement
Used in converging pointer problems where you always move both pointers symmetrically.
WHILE left < right:
Process S[left] and S[right]
left += 1
right -= 1
When to use: Palindrome checking, string reversal—problems where you process symmetric pairs.
Strategy 2: Conditional Movement Based on Comparison
Used when the decision to move depends on evaluating the current state.
WHILE left < right:
IF condition_favors_left:
left += 1
ELSE:
right -= 1
When to use: Two-sum in sorted array (move left if sum too small, right if too large), container with most water.
Strategy 3: Fast Always Moves, Slow Conditionally
Used in filtering/partition problems.
FOR fast = 0 TO n-1:
IF should_keep(S[fast]):
S[slow] = S[fast]
slow += 1
When to use: Removing elements, deduplication, filtering characters.
Strategy 4: Expand/Contract Window
Used in sliding window problems (covered in next page). Right pointer expands the window, left pointer contracts it.
FOR right = 0 TO n-1:
// Expand window by including S[right]
WHILE window_invalid:
// Contract by excluding S[left]
left += 1
// Process valid window
| Strategy | Left Movement | Right Movement | Example Problem |
|---|---|---|---|
| Alternating | Always | Always | Palindrome check |
| Comparison-based | When condition A | When condition B | Two-sum sorted |
| Fast-slow | When keeping element | Always | Remove duplicates |
| Expand-contract | When shrinking window | Always | Sliding window |
Two-pointer algorithms can infinitely loop if neither pointer advances in some iteration. Always ensure that at least one pointer moves forward in every iteration (or that the loop terminates). A clear understanding of movement conditions prevents this bug.
Recognizing Two-Pointer Problems
Developing the instinct to recognize two-pointer problems is as important as knowing how to implement them. Here are the signals to watch for:
Signal 1: Symmetric or End-to-End Structure
Keywords: "palindrome," "symmetric," "reverse," "from both ends"
Why two pointers: Symmetric structures naturally pair first with last, second with second-to-last.
Signal 2: Sorted/Ordered Data
Keywords: "sorted array," "sorted string," "in order"
Why two pointers: Ordered data has monotonicity. Moving a pointer in one direction consistently increases or decreases some property, enabling binary-search-like elimination.
Signal 3: In-Place Modification with O(1) Space Constraint
Keywords: "in place," "constant extra space," "do not use additional array"
Why two pointers: In-place modification often requires distinguishing between "processed" and "unprocessed" regions—perfect for slow/fast pointers.
Signal 4: Finding Pairs or Subranges
Keywords: "find a pair," "find two elements," "subarray summing to," "contiguous substring"
Why two pointers: Pairs and ranges are defined by two positions. Two pointers let you explore the space of pairs/ranges efficiently.
Signal 5: Comparison/Merging from Two Sources
Keywords: "merge two sorted," "compare two strings from ends"
Why two pointers: When processing two sequences together, one pointer per sequence is natural.
- •"Check if string is a palindrome" → Converging pointers
- •"Reverse a string in place" → Converging pointers swapping
- •"Remove all instances of character in place" → Fast/slow pointers
- •"Find pair summing to target in sorted array" → Converging with conditional movement
- •"Merge two sorted strings" → Two pointers, one per string
- •"Longest substring without repeating characters" → Sliding window (next page)
- •"Container with most water" → Converging, move pointer with smaller height
- •"Backspace string compare" → Reverse direction with skip logic
Two pointers don't apply when: (1) there's no ordering or structure to exploit, (2) the problem inherently requires checking all pairs (no elimination possible), or (3) the problem is about individual elements rather than pairs/ranges. Force-fitting two pointers where they don't apply leads to incorrect or overly complex solutions.
String-Specific Considerations
When applying two-pointer techniques to strings (versus arrays of numbers), some string-specific concerns arise:
Consideration 1: Mutability
In many languages (Java, Python, JavaScript), strings are immutable. You cannot change a character in place. This affects in-place two-pointer algorithms:
Workarounds:
- Convert string to character array, manipulate, convert back
- Build output in a separate structure (loses O(1) space advantage)
- Use language-specific mutable string types (e.g., StringBuffer in Java)
In languages with mutable strings (C, C++), direct in-place modification is possible.
Consideration 2: Character Filtering
Many problems require ignoring certain characters (non-alphanumeric, spaces, punctuation). The two-pointer logic must skip these:
// Palindrome check ignoring non-letters
WHILE left < right:
WHILE left < right AND NOT isLetter(S[left]):
left += 1
WHILE left < right AND NOT isLetter(S[right]):
right -= 1
IF toLower(S[left]) ≠ toLower(S[right]):
RETURN false
left += 1
right -= 1
RETURN true
Consideration 3: Case Sensitivity
Comparing characters often requires case-insensitive matching. Always normalize (toLower or toUpper) before comparing.
Consideration 4: Unicode and Multi-Byte Characters
In Unicode strings, what appears as one character might be multiple code points (accent marks, emoji with modifiers). Indexing by code unit can produce incorrect results.
For interview problems: Usually, you can assume ASCII or simple Unicode. But in production code, be aware of grapheme clusters.
Consideration 5: String Length Checks
Always handle edge cases:
- Empty string (length 0): Usually trivially valid for palindrome, nothing to reverse, etc.
- Single character: Also trivially valid for symmetric properties
These checks should happen before pointer initialization to avoid out-of-bounds access.
Off-by-one errors are rampant in two-pointer code. Double-check: (1) Initial positions (0 and n-1, not 0 and n), (2) Loop termination (< vs <=), (3) Index updates (increment after or before processing?). Trace through examples on paper before coding.
KEEP LEARNING
Keep learning for free.
Read the complete lesson, save your notes and pick up where you left off with a free account. No card needed.