| layout | default |
|---|---|
| title | Strings |
| nav_order | 11 |
| has_children | true |
| permalink | /02_strings/ |
Immutable sequences of characters - fundamental for text processing
Strings Overview
| In one line | Immutable sequences of characters - fundamental for text processing |
| Difficulty | Easy to Hard |
| Subtopics | 4 |
| Problems | 50+ |
How to use this page: Start with the visual overview, scan At a Glance, then work through theory → walkthroughs → code.
| # | Topic | Problems | Link |
|---|---|---|---|
| 1 | Basic String | 10+ | 📖 Go → |
| 2 | Anagram Problems | 10+ | 📖 Go → |
| 3 | Palindrome | 12+ | 📖 Go → |
| 4 | Subsequence | 10+ | 📖 Go → |
A string
ASCII Encoding:
Memory:
Number of substrings of length
Total substrings (including empty):
Proof:
Substrings starting at position 0: n choices Substrings starting at position 1: n-1 choices ... Substrings starting at position n-1: 1 choice
Total = n + (n-1) + ... + 1 = n(n+1)/2 Plus 1 for empty string = n(n+1)/2 + 1 ∎
Theorem: Strings
Equivalent Conditions:
-
$\text{sorted}(S) = \text{sorted}(T)$ -
$\vec{f}(S) = \vec{f}(T)$ (frequency vectors equal) -
$|S| = |T|$ and$S$ is a permutation of$T$
Frequency Vector (for lowercase letters):
Proof:
Definition: String
Palindrome Centers Formula:
-
Odd length palindromes:
$n$ centers at indices$0, 1, \ldots, n-1$ -
Even length palindromes:
$n-1$ centers between indices
Expansion Formula:
For center at position
Proof of Center Count:
Recurrence Relation:
Operations Cost:
-
Delete from
$S$ :$dp[i-1][j] + 1$ -
Insert into
$S$ :$dp[i][j-1] + 1$ -
Replace in
$S$ :$dp[i-1][j-1] + 1$
Optimal Substructure Proof:
Let
Case 1: If
Case 2: If
-
Delete
$S[i-1]$ : match$S[0..i-2]$ with$T[0..j-1]$ →$E(i-1,j) + 1$ -
Insert
$T[j-1]$ : match$S[0..i-1]$ with$T[0..j-2]$ →$E(i,j-1) + 1$ -
Replace
$S[i-1]$ with$T[j-1]$ : match$S[0..i-2]$ with$T[0..j-2]$ →$E(i-1,j-1) + 1$
Take minimum → optimal ∎
State Definition:
Recurrence:
Base Case:
Properties:
Correctness Proof:
Optimal Substructure:
If
If
By induction on string lengths, DP computes optimal solution ∎
Hash Function:
Where:
-
$p$ is a prime (typically 31 for lowercase, 53 for mixed case) -
$m$ is a large prime ($10^9 + 7$ or$10^9 + 9$ )
Rolling Update (add character on right):
Rolling Update (remove character from left):
Collision Probability:
For two different strings:
Example Calculation:
For string "abc" with
Failure Function:
Recurrence:
Time Complexity Proof:
Let
-
Each successful match:
$k$ increases by 1 -
Each mismatch:
$k$ decreases (follows$\pi$ links) -
$k$ can increase at most$n$ times -
$k$ can decrease at most$n$ times (can't go negative)
Total operations:
Matching Time:
-
Understanding of arrays and hash maps
-
Familiarity with two pointers technique
-
Basic knowledge of dynamic programming
Week 1-2: Basic operations + Anagrams
Week 3-4: Palindromes + Sliding window
Week 5-6: DP problems (LCS, Edit distance)
| Operation | Time | Python | Java | Notes |
|---|---|---|---|---|
Access s[i] |
O(1) | ✓ | ✓ | Direct indexing |
| Length | O(1) | ✓ | ✓ | Cached |
Slice s[i:j] |
O(j-i) | ✓ | - | Creates new string |
| Concatenate | O(n+m) | ✓ | ✓ | New string created |
| Find substring | O(nm) | ✓ | ✓ | Naive; KMP is O(n+m) |
| Compare | O(n) | ✓ | ✓ | Character by character |
| Approach | Time | When to Use |
|---|---|---|
Repeated += |
O(n²) | ❌ Never |
| StringBuilder/List | O(n) | ✅ Multiple concatenations |
''.join() |
O(n) | ✅ Combining list of strings |
| # | Problem | Category | Difficulty | Why Important |
|---|---|---|---|---|
| 1 | Valid Anagram | Frequency | 🟢 Easy | Foundation pattern |
| 2 | Valid Palindrome | Two Pointers | 🟢 Easy | Most common |
| 3 | Longest Substring Without Repeating | Sliding Window | 🟡 Medium | Top interview |
| 4 | Longest Palindromic Substring | Expand Center | 🟡 Medium | Classic |
| 5 | Group Anagrams | Hash + Sort | 🟡 Medium | Real-world |
| 6 | Find All Anagrams | Sliding Window | 🟡 Medium | Window pattern |
| 7 | Palindromic Substrings | Expand Center | 🟡 Medium | Counting |
| 8 | Longest Common Subsequence | DP | 🟡 Medium | DP foundation |
| 9 | Reverse Words | Two Pointers | 🟡 Medium | Parsing |
| 10 | Palindrome Partitioning | Backtracking | 🟡 Medium | Combination |
| 11 | Minimum Window Substring | Sliding Window | 🔴 Hard | Hardest window |
| 12 | Edit Distance | DP | 🔴 Hard | Classic DP |
| 13 | Regular Expression Matching | DP | 🔴 Hard | Pattern matching |
| 14 | Distinct Subsequences | DP | 🔴 Hard | Counting DP |
| 15 | Longest Valid Parentheses | Stack/DP | 🔴 Hard | Multiple approaches |
| # | Problem | Technique | Time | Space |
|---|---|---|---|---|
| 14 | Longest Common Prefix | Vertical Scan | O(mn) | O(1) |
| 28 | Find Index of First Occurrence | KMP | O(n+m) | O(m) |
| 125 | Valid Palindrome | Two Pointers | O(n) | O(1) |
| 242 | Valid Anagram | Counter | O(n) | O(1) |
| 344 | Reverse String | Two Pointers | O(n) | O(1) |
| 387 | First Unique Character | Counter | O(n) | O(1) |
| 392 | Is Subsequence | Two Pointers | O(n) | O(1) |
| # | Problem | Technique | Time | Space |
|---|---|---|---|---|
| 3 | Longest Substring Without Repeating | Sliding Window | O(n) | O(k) |
| 5 | Longest Palindromic Substring | Expand Center | O(n²) | O(1) |
| 22 | Generate Parentheses | Backtracking | O(4ⁿ/√n) | O(n) |
| 49 | Group Anagrams | Hash + Sort | O(nk log k) | O(nk) |
| 131 | Palindrome Partitioning | Backtracking | O(n⋅2ⁿ) | O(n) |
| 151 | Reverse Words in a String | Two Pointers | O(n) | O(n) |
| 438 | Find All Anagrams | Sliding Window | O(n) | O(1) |
| 647 | Palindromic Substrings | Expand Center | O(n²) | O(1) |
| 1143 | Longest Common Subsequence | DP | O(mn) | O(mn) |
| # | Problem | Technique | Time | Space |
|---|---|---|---|---|
| 10 | Regular Expression Matching | DP | O(mn) | O(mn) |
| 32 | Longest Valid Parentheses | Stack/DP | O(n) | O(n) |
| 72 | Edit Distance | DP | O(mn) | O(mn) |
| 76 | Minimum Window Substring | Sliding Window | O(n) | O(k) |
| 115 | Distinct Subsequences | DP | O(mn) | O(mn) |
🎯 String Immutability
Strings are immutable in Python/Java. Use StringBuilder or list for O(n) instead of O(n²) concatenation.
⚡ Fixed Alphabet Optimization
For 26 lowercase letters, useint[26]instead of HashMap for O(1) space and better constants.
🔄 Palindrome Centers
Always remember 2n-1 centers. This is the key to O(n²) palindrome problems.
📊 Sliding Window Template
expand right → add to window while (invalid) → contract left update answer
🔍 DP on Strings Pattern
dp[i][j]usually means "answer for S[0..i-1] and T[0..j-1]". Match chars or skip, take optimal.
| If Problem Says... | Think... | Examples |
|---|---|---|
| "valid palindrome" | Two Pointers | #125, #680 |
| "anagram" or "permutation" | Character Frequency | #242, #49, #567 |
| "longest substring without..." | Sliding Window + Set | #3 |
| "find all anagrams" | Sliding Window + Frequency | #438 |
| "palindromic substrings" | Expand Around Center | #5, #647 |
| "partition" | Backtracking + Palindrome Check | #131 |
| "longest common subsequence" | 2D DP | #1143 |
| "edit distance" | 2D DP | #72 |
| "minimum window" | Sliding Window | #76 |
| "pattern matching" | KMP or DP | #28, #10 |
| Resource | Description | Link |
|---|---|---|
| CLRS Chapter 32 | String matching algorithms | MIT Press |
| Algorithms on Strings | Comprehensive textbook | Cambridge |
| Competitive Programming 3 | Chapter 6: String processing | Book |
| Algorithms 4th Edition | Sedgewick & Wayne | Book Site |
| Resource | Description | Link |
|---|---|---|
| CP-Algorithms | String algorithms encyclopedia | Strings |
| GeeksforGeeks | String tutorials & problems | Strings |
| LeetCode Explore | String learning path | Card |
| HackerEarth | String algorithms tutorial | Tutorial |
| Resource | Topic | Link |
|---|---|---|
| NeetCode | String patterns playlist | YouTube |
| Abdul Bari | KMP algorithm explained | YouTube |
| Back To Back SWE | String problems series | YouTube |
| William Fiset | String algorithms | YouTube |
| MIT OCW 6.006 | String matching lecture | MIT |
| Tushar Roy | DP on strings | YouTube |
| Platform | Focus | Link |
|---|---|---|
| LeetCode | Interview problems | String Tag |
| HackerRank | String manipulation | Practice |
| Codeforces | Competitive programming | String Problems |
| CodeChef | Monthly contests | Strings |
| AtCoder | Japanese contests | Problems |
| Topic | Description | Link |
|---|---|---|
| KMP Algorithm | O(n+m) pattern matching | Wikipedia |
| Rabin-Karp | Rolling hash technique | GeeksforGeeks |
| Manacher's Algorithm | O(n) longest palindrome | CP-Algorithms |
| Aho-Corasick | Multiple pattern matching | Wikipedia |
| Suffix Array | Advanced string structure | CP-Algorithms |
| Suffix Tree | Generalized suffix structure | GeeksforGeeks |
| Z-Algorithm | String matching in O(n) | CP-Algorithms |
| Boyer-Moore | Fast pattern matching | Wikipedia |
| Collection | Focus | Link |
|---|---|---|
| NeetCode 150 | Curated interview problems | Strings |
| Blind 75 | Essential coding problems | List |
| Grind 75 | Week-by-week preparation | Guide |
| Striver's SDE Sheet | Must-do problems | Sheet |
| LeetCode Patterns | 14 patterns guide | Sean Prashad |
| Tool | Purpose | Link |
|---|---|---|
| Regex101 | Regular expressions tester | Website |
| VisuAlgo | String algorithms visualization | Suffix Array |
| Algorithm Visualizer | Step-by-step execution | Website |
| String Matching Viz | Pattern matching demo | Tool |
| Resource | Topic | Link |
|---|---|---|
| USACO Guide | String algorithms guide | Guide |
| TopCoder | Tutorials & editorials | Articles |
| Codeforces EDU | Educational courses | Course |
| CSES Problem Set | Finnish platform | Strings |
| Paper | Topic | Link |
|---|---|---|
| Knuth-Morris-Pratt (1977) | Original KMP paper | Paper |
| Manacher (1975) | Linear time palindromes | Paper |
| Levenshtein (1966) | Edit distance | Paper |
❌ Don't:
-
Concatenate strings in loops without StringBuilder
-
Forget about empty string edge case
-
Ignore case sensitivity requirements
-
Use nested loops when sliding window works
-
Forget to handle Unicode characters
✅ Do:
-
Use StringBuilder/list for multiple concatenations
-
Test with edge cases: empty, single char, all same
-
Clarify case sensitivity and special characters
-
Recognize sliding window patterns early
-
Consider both ASCII and Unicode
- Can I use character array instead of HashMap?
- Is sliding window applicable?
- Should I use expand-around-center for palindromes?
- Is this a DP problem? (LCS, edit distance patterns)
- Can rolling hash optimize substring search?
- Am I avoiding O(n²) string concatenation?
"Strings are everywhere - from DNA sequences to search engines. Master them, and you master text processing."
Progress Tracker:
-
🥉 Bronze: Solve 20 string problems
-
🥈 Silver: Solve 50 string problems
-
🥇 Gold: Solve 100 string problems
-
💎 Platinum: Can explain KMP and solve hard DP problems
Remember: Every string algorithm you learn makes you a better programmer! 💪
Made with ❤️ for the coding community by Gaurav Goswami
⬅️ Previous: Arrays | 🏠 Home | Next: Linked Lists ➡️
Last Updated: December 2025
Licensed under MIT
Happy Coding! 💻✨


