DSA Guide
Strings

Strings

Character counting, two pointers and normalisation — the recurring shapes of string problems

Strings are arrays of characters, so most array techniques carry over directly. What makes string problems distinct is that the content often has structure worth exploiting — letters have counts, words have boundaries, and equivalent strings can be reduced to a shared canonical form.

The Patterns

1. Counting — reduce a string to a multiset

Once you only care about which characters and how many, order stops mattering and the problem usually becomes easy.

Sets lose multiplicity

The most common bug in this family is using a set where counts are needed. "step" has an s; it does not have two. If the problem cares how many times something appears, count it.

2. Two pointers — walk from both ends or at different rates

3. Normalisation — make equivalent strings identical

Rather than asking "are these equivalent?", transform both into a canonical form and ask "are these equal?".

4. Simulation — follow the specification exactly

Some problems have no clever insight; the challenge is holding a fiddly rule set straight.

Language Gotchas Worth Memorising

SituationPythonTypeScript
Split on whitespace, dropping emptiess.split()s.trim().split(/\s+/)
Split on a single space (keeps empties)s.split(" ")s.split(" ")
Reverse a strings[::-1][...s].reverse().join("")
Integer divisiona // bMath.floor(a / b)
Truncate toward zeroint(a / b)Math.trunc(a / b)
Count charactersCounter(s)a Map built by hand
Missing key returns 0Counter[k]map.get(k) ?? 0

Build strings with join, not +=

Repeated result += char inside a loop allocates a new string each iteration — O(n²) overall. Collect pieces in a list and join once.

All Problems

ProblemDifficultyPattern
Valid PalindromeEasyTwo Pointers
Valid AnagramEasyCounting
Longest Common PrefixEasyVertical Scan
Length of Last WordEasyReverse Scan
Roman to IntegerEasyLocal Comparison
Is SubsequenceEasyTwo Pointers
Isomorphic StringsEasyTwo Hash Maps
Longest PalindromeEasyCounting
First Occurrence in a StringEasyString Matching
Keyboard RowEasyHash Map
Shortest Completing WordEasyCounting
Unique Email AddressesEasyNormalisation
Palindrome NumberEasyDigit Math
Integer to RomanMediumGreedy
Reverse Words in a StringMediumTwo Pointers
Zigzag ConversionMediumSimulation
Text JustificationHardSimulation

On this page