String Algorithms (12 problems)
12 Problems with Guidance Only (NO Solutions)
Purpose: Master string manipulation for technical interviews Difficulty: ⭐ Easy → ⭐⭐⭐⭐ Hard Time per problem: 20-45 minutes
Problem 151: Reverse String (3 Methods) ⭐⭐
Problem Statement:
Write a function that reverses a string. Implement THREE different approaches:
Using iteration
Using recursion
Using built-in methods
Examples:
Input: "hello"
Output: "olleh"
Input: "C#"
Output: "#C"
Input: "a"
Output: "a"
Input: ""
Output: ""Constraints:
0 ≤ string.length ≤ 10⁴
String contains ASCII characters
Approach 1: Two Pointers (Iteration)
Concept:
Use two pointers: one at start, one at end
Swap characters and move pointers toward center
Convert string to char array first (strings are immutable)
Complexity:
Time: O(n)
Space: O(n) - for char array
Hints:
Approach 2: Recursion
Concept:
Base case: empty or single character
Recursive case: first char + reverse(rest of string)
Complexity:
Time: O(n)
Space: O(n) - recursion stack + string concatenation
Hints:
Approach 3: Built-in Methods
Concept:
Use Array.Reverse() or LINQ
Hints:
Test Cases:
Interview Tips:
Show you know multiple approaches
Mention string immutability
Discuss which method is most efficient
Production code: use built-in methods
Interview: show you can implement from scratch
Problem 152: Check Anagrams ⭐⭐
Problem Statement:
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram is a word formed by rearranging the letters of another word, using all original letters exactly once.
Examples:
Constraints:
1 ≤ s.length, t.length ≤ 5 × 10⁴
s and t consist of lowercase English letters
Approach 1: Sorting
Concept:
Sort both strings
Compare if sorted versions are equal
Complexity:
Time: O(n log n)
Space: O(1) or O(n) depending on sorting
Hints:
Approach 2: Frequency Map (Optimal)
Concept:
Count frequency of each character
Both strings should have same character frequencies
Complexity:
Time: O(n)
Space: O(1) - at most 26 letters
Hints:
Approach 3: Single Pass (Optimized)
Concept:
Use array of size 26 for lowercase letters
Increment for first string, decrement for second
Check if all values are zero
Hints:
Test Cases:
Common Mistakes:
Not checking lengths first (quick optimization)
Case sensitivity (problem says lowercase, but ask!)
Unicode characters (problem says English letters)
Interview Tips:
Always check lengths first (O(1) optimization)
Mention both approaches
Sorting is simpler code but slower
Hash map is optimal
Problem 153: First Non-Repeating Character ⭐⭐
Problem Statement:
Given a string s, find the first non-repeating character and return its index. If it doesn't exist, return -1.
Examples:
Constraints:
1 ≤ s.length ≤ 10⁵
s consists of lowercase English letters
Approach 1: Brute Force
Concept:
For each character, check if it appears elsewhere
Return first character that doesn't repeat
Complexity:
Time: O(n²)
Space: O(1)
Not recommended for interview!
Approach 2: Two Pass with Dictionary (Optimal)
Concept:
First pass: count frequency of each character
Second pass: find first character with frequency 1
Complexity:
Time: O(n)
Space: O(1) - at most 26 letters
Hints:
Approach 3: Array Instead of Dictionary
Concept:
Use int[26] for lowercase letters
Faster than Dictionary for this use case
Hints:
Test Cases:
Interview Tips:
Explain why two passes are needed
Mention array vs Dictionary trade-off
Array is faster for known small character set
Dictionary is more flexible for Unicode
Problem 154: Longest Substring Without Repeating Characters ⭐⭐⭐
Problem Statement:
Given a string s, find the length of the longest substring without repeating characters.
Examples:
Constraints:
0 ≤ s.length ≤ 5 × 10⁴
s consists of English letters, digits, symbols, and spaces
Approach 1: Brute Force
Concept:
Check all possible substrings
For each, verify if all characters are unique
Complexity:
Time: O(n³)
Space: O(min(n, m)) where m is character set size
Too slow!
Approach 2: Sliding Window with HashSet (Optimal)
Key Insight:
Use two pointers (left and right)
Expand window by moving right
Contract window when duplicate found
Track maximum length seen
Concept:
HashSet stores characters in current window
When duplicate found, remove from left until no duplicate
Update max length at each step
Complexity:
Time: O(n) - each character visited at most twice
Space: O(min(n, m)) - HashSet size
Hints:
Approach 3: Sliding Window with Dictionary (Optimized)
Concept:
Store character → last seen index
When duplicate found, jump left pointer directly
Complexity:
Time: O(n) - single pass
Space: O(min(n, m))
Hints:
Test Cases:
Common Mistakes:
Not handling empty string
Off-by-one errors with left pointer
Forgetting to update maxLength
Not using Math.Max when moving left pointer
Interview Tips:
Start by explaining brute force (shows understanding)
Draw the sliding window movement
Explain why each character is visited at most twice
Mention the optimization with Dictionary
Problem 155: String Compression (aaabb → a3b2) ⭐⭐
Problem Statement:
Implement basic string compression using the counts of repeated characters.
For example: "aabcccccaaa" becomes "a2b1c5a3"
If the compressed string is not smaller than the original, return the original string.
Examples:
Constraints:
1 ≤ s.length ≤ 10⁴
s consists of lowercase English letters
Approach: Single Pass with StringBuilder
Concept:
Iterate through string counting consecutive characters
When character changes, append count to result
Compare final length with original
Complexity:
Time: O(n)
Space: O(n) - StringBuilder
Hints:
Test Cases:
Common Mistakes:
Forgetting last character group
Not comparing lengths before returning
Using string concatenation instead of StringBuilder (slow!)
Interview Tips:
Mention StringBuilder for performance
Handle edge case: single character
Ask: "Should single occurrences show '1'?" (Yes in this version)
Problem 156: Longest Palindromic Substring ⭐⭐⭐⭐
Problem Statement:
Given a string s, return the longest palindromic substring in s.
Examples:
Constraints:
1 ≤ s.length ≤ 1000
s consists of lowercase English letters
Approach 1: Brute Force
Concept:
Check all possible substrings
For each, check if palindrome
Complexity:
Time: O(n³)
Space: O(1)
Too slow!
Approach 2: Expand Around Center (Optimal for this problem)
Key Insight:
Palindromes mirror around center
Center can be single character (odd length) or between two characters (even length)
Expand outward from each possible center
Concept:
For each position, try expanding as center
Track longest palindrome found
Complexity:
Time: O(n²) - n centers × n expansion
Space: O(1)
Hints:
Approach 3: Dynamic Programming
Concept:
dp[i][j] = true if substring from i to j is palindrome
dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1]
Complexity:
Time: O(n²)
Space: O(n²)
Hints:
Test Cases:
Common Mistakes:
Forgetting even-length palindromes
Off-by-one errors in expansion
Not handling single character
Interview Tips:
Explain expand-around-center approach (most intuitive)
Mention DP exists but more complex
Draw example of expansion
Discuss time-space trade-offs
Problem 157: Valid Parentheses ⭐⭐
Problem Statement:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Valid means:
Open brackets must be closed by the same type
Open brackets must be closed in the correct order
Every close bracket has a corresponding open bracket
Examples:
Constraints:
1 ≤ s.length ≤ 10⁴
s consists of parentheses only '()[]{}'
Approach: Stack
Key Insight:
Most recent open bracket must match next close bracket
This is LIFO (Last In, First Out) → Stack!
Concept:
Push open brackets onto stack
For close bracket: check if matches top of stack
At end, stack should be empty
Complexity:
Time: O(n)
Space: O(n) - stack size
Hints:
Optimization: Use Dictionary for Matching
Test Cases:
Common Mistakes:
Not checking if stack is empty before popping
Not checking if stack is empty at the end
Forgetting edge case: empty string
Interview Tips:
Stack is THE data structure for matching problems
Explain LIFO property
Walk through example visually
Mention variations: min stack, next greater element, etc.
Problem 158: String Permutations ⭐⭐⭐
Problem Statement:
Given a string s, return all possible permutations of its characters.
Examples:
Constraints:
1 ≤ s.length ≤ 8
s consists of unique lowercase English letters
Approach: Backtracking
Key Insight:
For each position, try every remaining character
Recurse for rest of positions
Backtrack when done
Concept:
Fix first character, permute rest
Swap characters to try different first characters
Recursively build permutations
Complexity:
Time: O(n × n!) - n! permutations, n to build each
Space: O(n!) - storing all permutations
Hints:
Test Cases:
Interview Tips:
Draw the recursion tree
Explain backtracking concept
Mention time complexity (factorial!)
Discuss duplicate handling (if chars not unique)
Problem 159: String Rotation Check ⭐⭐
Problem Statement:
Check if one string is a rotation of another.
Example: "waterbottle" is a rotation of "erbottlewat"
Examples:
Approach 1: Brute Force
Concept:
Try all possible rotations of s1
Check if any matches s2
Complexity:
Time: O(n²)
Space: O(n)
Approach 2: Clever Trick (Optimal)
Key Insight:
If s2 is rotation of s1, then s2 is substring of s1+s1!
Example: "waterbottle" + "waterbottle" = "waterbottlewaterbottle"
"erbottlewat" is substring of above!
Concept:
Check if lengths are equal (must be for rotation)
Check if s2 is substring of s1 + s1
Complexity:
Time: O(n)
Space: O(n)
Hints:
Test Cases:
Interview Tips:
Start with brute force to show understanding
Then present the clever trick
Explain why it works with example
Mention this is a common interview trick
Problem 160: Longest Common Prefix ⭐⭐
Problem Statement:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Examples:
Constraints:
1 ≤ strs.length ≤ 200
0 ≤ strs[i].length ≤ 200
strs[i] consists of lowercase English letters
Approach 1: Vertical Scanning
Concept:
Compare characters at same position across all strings
Stop when mismatch found or any string ends
Complexity:
Time: O(S) where S is sum of all characters
Space: O(1)
Hints:
Approach 2: Horizontal Scanning
Concept:
Start with first string as prefix
For each subsequent string, reduce prefix until it matches
Hints:
Test Cases:
Interview Tips:
Both approaches are valid
Vertical scanning is more intuitive
Handle edge cases: empty array, empty strings
Mention early termination optimization
Problem 161: Implement atoi (String to Integer) ⭐⭐⭐
Problem Statement:
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
Algorithm:
Read in and ignore leading whitespace
Check if next character is '-' or '+' (determines sign)
Read digits until non-digit or end of input
Convert to integer
Clamp to [−2³¹, 2³¹ − 1]
Examples:
Approach: State Machine
Concept:
Trim whitespace
Handle sign
Build number digit by digit
Check for overflow
Complexity:
Time: O(n)
Space: O(1)
Hints:
Test Cases:
Common Mistakes:
Not handling overflow correctly
Not stopping at first non-digit
Not handling '+' sign
Not handling leading zeros
Interview Tips:
This tests edge case handling
Use long to detect overflow
Be thorough with test cases
Ask about leading zeros, multiple signs, etc.
Problem 162: Regex Email Validator ⭐⭐
Problem Statement:
Validate if a string is a valid email address using basic rules:
Local part (before @): letters, digits, dots, hyphens, underscores
Domain part (after @): letters, digits, dots
At least one dot in domain
No consecutive dots
Examples:
Approach 1: Manual Validation
Concept:
Check for single @
Validate local part
Validate domain part
Hints:
Approach 2: Regex Pattern
Concept:
Use regular expression pattern
Hints:
Test Cases:
Interview Tips:
Start with manual approach
Then show regex (if you know it)
Mention this is simplified version
Real email validation is VERY complex
In production: use libraries
✅ Track A Complete!
You've covered 12 essential string algorithm problems. Practice these until you can solve them confidently without hints!
Next: Track B - Array Algorithms (15 problems)
Last updated