String Interview Problems
Picture this. 🎯 You're sitting in a coding interview. The interviewer smiles and says:
"Can you write a function to check if a string has valid brackets?"
Your heart beats a little faster. 😅 But then you remember: string problems follow patterns. Once you know the patterns, most questions become familiar friends.
In this lesson, you'll practise 16 popular interview questions on strings, from warm-ups to the ones that big companies love to ask.
How to Use This Lesson
For every problem:
- 📖 Read the problem and the examples.
- 🤔 Think about how you'd solve it by hand first.
- ⌨️ Try it yourself in the playground.
- ✅ Then read the idea and the solution.
In a real interview, talk through your thinking out loud. Interviewers care about how you think, not just the final code. 🗣️
The 6 Patterns You'll Use Again and Again 🧠
Almost every string problem uses one (or more) of these:
| Pattern | Idea | Example problems |
|---|---|---|
| Split → change → join | Turn the string into an array, work on it, join it back | Reverse words |
| Frequency map | Count characters in an object or Map | Anagrams, first unique character |
| Two pointers | Two positions moving towards each other | Palindromes |
| Sliding window | A "window" that grows and shrinks over the string | Longest substring without repeats |
| Stack | Last in, first out, like a pile of plates | Valid brackets |
| Expand around the centre | Grow outward from each position | Longest palindrome |
A quick word on speed (Big-O) ⏱️
Interviewers often ask, "How fast is your solution?" We describe this with Big-O, where n is the length of the string:
| Big-O | Meaning | Real-life feel |
|---|---|---|
O(n) | Look at each character once | Reading a sentence once 🟢 |
O(n log n) | Usually means sorting | Arranging cards in order 🟡 |
O(n²) | A loop inside a loop | Comparing every student with every other student 🔴 |
Aim for
O(n)when you can, but a workingO(n²)solution is always better than no solution!
🟢 Warm-Up Round
Problem 1: Reverse Words in a Sentence
Task: Reverse the order of the words, not the letters. Remove extra spaces.
Examples:
"I love JavaScript"→"JavaScript love I"" hello world "→"world hello"
💡 Idea: Split → change → join. Trim the ends, split on one or more spaces, reverse the array, and join with a single space.
⏱️ Time: O(n)
Follow-up the interviewer might ask: "Reverse the letters of each word, but keep the word order."
Problem 2: Valid Anagram
Task: Return true if two strings contain exactly the same letters, in any order.
Examples:
"listen","silent"→true"rat","car"→false
💡 Idea: Frequency map. Count every letter in the first word, then subtract for every letter in the second. If everything comes back to zero, they're anagrams.
⏱️ Time: O(n)
💡 A shorter answer is to sort both strings and compare them, but that's
O(n log n). Mention both in an interview. It shows you know the trade-offs!
Problem 3: Longest Common Prefix
Task: Find the longest starting part that all the words share.
Examples:
["flower", "flow", "flight"]→"fl"["dog", "car", "race"]→""
💡 Idea: Start by assuming the whole first word is the prefix. For each other word, keep cutting the prefix shorter until the word starts with it.
Problem 4: Check if One String Is a Rotation of Another
Task: Is b a rotation of a? A rotation moves some characters from the front to the back.
Examples:
"waterbottle","erbottlewat"→true"hello","lohel"→true"hello","olleh"→false
💡 Idea: Here's a clever trick 🪄. If you join a with itself, every possible rotation appears inside it!
a + a = "hellohello"
↑↑↑↑↑
"lohel" is inside ✅
🟡 Medium Round
Problem 5: Valid Palindrome (Ignoring Symbols)
Task: Check if a sentence reads the same forwards and backwards, ignoring case, spaces, and punctuation.
Examples:
"A man, a plan, a canal: Panama"→true"race a car"→false
💡 Idea: Two pointers. One starts at the left, one at the right. Skip anything that isn't a letter or number. Compare the characters and move inward. It's like two friends walking towards each other and checking that they're holding the same card. 🃏
⏱️ Time: O(n). It also uses no extra copy of the string, which interviewers like!
Problem 6: Valid Parentheses ⭐
Task: Check if every bracket ( ) { } [ ] is closed in the correct order.
Examples:
"()[]{}"→true"{[()]}"→true"(]"→false"([)]"→false
💡 Idea: Use a stack 🍽️, like a pile of plates. Every opening bracket goes on top of the pile. When you see a closing bracket, the top plate must match. If it doesn't, it's invalid. At the end, the pile must be empty.
"{[()]}"
{ push → [ { ]
[ push → [ {, [ ]
( push → [ {, [, ( ]
) pop ( ✅ → [ {, [ ]
] pop [ ✅ → [ { ]
} pop { ✅ → [ ] empty → valid!
⏱️ Time: O(n)
Problem 7: Group Anagrams Together
Task: Group words that are anagrams of each other.
Example: ["eat", "tea", "tan", "ate", "nat", "bat"]
→ [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
💡 Idea: Anagrams look identical when their letters are sorted: "eat", "tea", and "ate" all become "aet". Use that sorted version as a key in an object, and collect the words under it.
Problem 8: First Non-Repeating Character
Task: Return the index of the first character that appears only once, or -1 if there isn't one.
Examples:
"leetcode"→0("l")"loveleetcode"→2("v")"aabb"→-1
💡 Idea: Frequency map, two passes. First, count everything. Then walk again and return the first character with a count of 1.
Problem 9: String Compression
Task: Compress repeated characters as character + count. If the result isn't shorter, return the original.
Examples:
"aabcccccaaa"→"a2b1c5a3""abc"→"abc"(compressed"a1b1c1"is longer)
💡 Idea: Walk through the string. Count how many times the same character repeats in a row. When it changes, save the character and its count. Build the result in an array and join once at the end, because strings are immutable.
Problem 10: Isomorphic Strings
Task: Two strings are isomorphic if the letters of one can be replaced to get the other, with each letter always mapping to the same letter.
Examples:
"egg","add"→true(e→a, g→d)"foo","bar"→false(o can't be both a and r)"paper","title"→true
💡 Idea: Keep two maps: one from s to t, and one from t to s. If any letter tries to map to two different letters, it's not isomorphic. It's like a secret code 🔐: each letter must always have the same code letter.
Problem 11: Roman Numerals to Numbers 🏛️
Task: Convert a Roman numeral to a normal number.
| Symbol | I | V | X | L | C | D | M |
|---|---|---|---|---|---|---|---|
| Value | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
Examples:
"III"→3"IX"→9"MCMXCIV"→1994
💡 Idea: Usually you add each value. But when a smaller value comes before a bigger one (like I before X in IX), you subtract it instead.
Problem 12: Word Pattern
Task: Check if a sentence follows a pattern, where each letter matches exactly one word.
Examples:
- pattern
"abba", text"dog cat cat dog"→true - pattern
"abba", text"dog cat cat fish"→false - pattern
"aaaa", text"dog cat cat dog"→false
💡 Idea: This is Problem 10 in disguise! 🎭 Instead of mapping letter → letter, map letter → word.
🧠 Interview tip: Spotting that a new problem is an old problem in disguise is a superpower. Always ask yourself, "Have I seen something like this before?"
🔴 Interview Favourites
Problem 13: Longest Substring Without Repeating Characters ⭐⭐
This is one of the most asked string questions of all time!
Task: Find the length of the longest continuous part of the string with no repeated characters.
Examples:
"abcabcbb"→3("abc")"bbbbb"→1("b")"pwwkew"→3("wke")
💡 Idea: Sliding window 🪟. Imagine a window sliding over the string.
- Move the right edge forward, one character at a time.
- If the new character is already inside the window, move the left edge just past its earlier position.
- Track the biggest window you've seen.
Think of a train compartment 🚃 where no two passengers can have the same name. When someone new boards with a name that's already inside, people at the front get off until the old one with that name has left.
"abcabcbb"
[abc]abcbb window "abc" → size 3
[bca]bcbb "a" repeated → left moves → size 3
[cab]cbb "b" repeated → left moves → size 3
... best stays 3
⏱️ Time: O(n). Each character is visited only once. 🚀
Problem 14: Longest Palindromic Substring ⭐⭐
Task: Find the longest part of the string that is a palindrome.
Examples:
"babad"→"bab"(or"aba")"cbbd"→"bb""forgeeksskeegfor"→"geeksskeeg"
💡 Idea: Expand around the centre. Every palindrome has a middle. Try every position as a middle and grow outward while both sides match, like ripples 🌊 spreading out from a stone dropped in water.
There are two kinds of middles:
- Odd length, one centre character:
"aba"→ centreb - Even length, the centre is between two characters:
"abba"→ centre betweenbandb
⏱️ Time: O(n²), which is the expected answer in most interviews.
Problem 15: Count and Say 🗣️
Task: Each term describes the previous one out loud.
1 → "one 1" → 11
11 → "two 1s" → 21
21 → "one 2, one 1" → 1211
1211 → "one 1, one 2, two 1s" → 111221
Find the nth term.
💡 Idea: It's string compression (Problem 9) again, just with the count first and the character second! Repeat it n - 1 times.
Problem 16: Minimum Window Substring ⭐⭐⭐ (Challenge!)
This is a hard one, often asked at top companies. Don't worry if it takes a few tries! 💪
Task: Find the smallest part of s that contains all the characters of t (including duplicates).
Examples:
s = "ADOBECODEBANC",t = "ABC"→"BANC"s = "a",t = "aa"→""(not enoughas)
💡 Idea: Sliding window again, but smarter.
- Move the right edge to grow the window until it contains everything in
t. - Then move the left edge to shrink it as small as possible, while it still contains everything.
- Record the smallest valid window. Repeat.
It's like packing a school bag 🎒: first grab things until you have everything on the list, then take out anything extra you don't need.
⏱️ Time: O(n). Each character enters and leaves the window at most once.
🎯 Practice Challenges (Try Yourself!)
No solutions this time. You've got this! 💪
- Reverse vowels only:
"hello"→"holle"(Hint: two pointers) - Most frequent character:
"programming"→"g"(or"r"/"m"on a tie) - Check if a string has all unique characters, without using a
Set. - Longest word made of letters only: ignore numbers and symbols.
- Valid palindrome II: Can the string become a palindrome by removing at most one character?
"abca"→true - Integer to Roman:
1994→"MCMXCIV"(the reverse of Problem 11) - Find all anagrams: Find every starting index in
"cbaebabacd"where an anagram of"abc"begins →[0, 6](Hint: sliding window of fixed size)
🗣️ Interview Tips for String Questions
- Ask questions first. "Is it case-sensitive? Can there be spaces? What about an empty string?" Interviewers love this.
- Start simple. Give a working brute-force answer, then say "Now let me make it faster."
- Test edge cases out loud: empty string
"", one character"a", all the same"aaaa", and spaces or symbols. - Remember that strings are immutable. Building a big result with
+=in a loop creates many new strings. Collecting pieces in an array and usingjoin()once is a nice touch. - Name your pattern. Saying "I'll use a sliding window here" shows real experience. 🏆
Pattern Cheat Sheet
| If the problem says... | Think of... |
|---|---|
| "same letters", "anagram", "count", "frequency" | Frequency map |
| "reads the same backwards", "compare both ends" | Two pointers |
| "longest / shortest substring with..." | Sliding window |
| "brackets", "matching", "nested" | Stack |
| "longest palindrome" | Expand around the centre |
| "each X maps to one Y" | Two maps (both directions) |
| "reverse words", "capitalise words" | Split → change → join |
Key Takeaways
- Most string interview questions use a small set of patterns: frequency maps, two pointers, sliding windows, stacks, and expanding around the centre.
- Frequency maps solve anagram and uniqueness problems in
O(n), and a stack is the go-to tool for matching brackets. - The sliding window pattern turns "longest/shortest substring" problems from
O(n²)intoO(n). - Many "new" problems are old ones in disguise, like Word Pattern (isomorphic strings) and Count and Say (compression).
- In interviews, think out loud, start simple, test edge cases, and then improve your solution. 🚀