Leetcode String Patterns
1. Two Pointers
Used for comparing characters, reversing strings, or moving inward from both ends.
Common problems:
- Reverse String
- Valid Palindrome
- Merge Strings Alternately
Template:
left, right = 0, len(s) - 1
while left < right:
# Swap or compare
left += 1
right -= 1
2. Sliding Window
Ideal for substring problems or character frequency tracking.
Common problems:
- Longest Substring Without Repeating Characters
- Minimum Window Substring
- Find All Anagrams in a String
Template:
window = {}
left = 0
for right in range(len(s)):
# Expand window
while condition_not_met:
# Shrink window from left
left += 1
3. String Reversal / Word Order
Used when rearranging word or character order.
Common problems:
Leetcode String Patterns
- Reverse Words in a String
- Reverse String II
- Reverse Words III
Example:
" ".join(s.split()[::-1])
4. Character Frequency / Counting
Used for comparing string structures.
Common problems:
- Valid Anagram
- Group Anagrams
- Palindrome Permutation
Example:
from collections import Counter
Counter(s)
5. Pattern Matching / Mapping
Used for bijective mapping between characters or words.
Common problems:
- Isomorphic Strings
- Word Pattern
Example:
map_s_to_t = {}
map_t_to_s = {}
6. Dynamic Programming on Strings
Complex string transformations.
Common problems:
- Longest Palindromic Substring
- Edit Distance
Leetcode String Patterns
- Decode Ways
Technique: Build a 2D dp table.
7. Regex / Parsing
For structured string validation or transformation.
Common problems:
- Valid Number
- Reformat Date
- Simplify Path
Example:
import re
re.match(r"\d+", s)
8. String Construction / Simulation
Simulate building or converting strings.
Common problems:
- Count and Say
- Multiply Strings
- Integer to Roman / Roman to Integer
Use loops and conditions to build new strings.