Stop 21 · Data Structures & AlgorithmsTopics · 2/17

Strings

Part of the Frontend Developer Roadmap

In short

Palindromes, anagrams, reversing words. String questions look different but use a small set of tricks. Learn character counting and you've covered a big chunk of them.

Text-processing problems — often array problems in disguise, but with their own common patterns around characters, substrings and comparisons.

The jaadu sorts two piles of coins into matching stacks on a shop counter.

Think of it like this

Counting coins at a kirana store

Two piles of coins are worth the same if they have the same number of ₹1, ₹2 and ₹5 coins, whatever the order. Anagrams work the same way: count each letter, then compare the counts.

Watch it happen

Is 'silent' an anagram of 'listen'?

l
0
i
1
s
2
t
3
e
4
n
5

1/5First pass: count every letter of 'listen'. l, i, s, t, e and n each get a count of 1.

The big ideas

What you need to know

Strings can't be changed

In JS, s[0] = 'x' does nothing. Every change makes a new string, so build big ones with an array and join.

Count with a Map or array

A frequency count of characters solves anagrams, first unique character and many more in O(n).

Two pointers work here too

Check a palindrome by comparing the first and last characters and moving inwards.

Clean the input first

Lowercase it and strip spaces or symbols if the question says to ignore them.

See it in code

Walk through the code

js
1function isAnagram(a, b) {2  if (a.length !== b.length) return false;3 4  const count = new Map();5  for (const ch of a) count.set(ch, (count.get(ch) ?? 0) + 1);6 7  for (const ch of b) {8    const left = (count.get(ch) ?? 0) - 1;9    if (left < 0) return false;10    count.set(ch, left);11  }12  return true;13}14 15isAnagram("listen", "silent"); // true

1/4Different lengths can never be anagrams, so exit early.

Two passes over the strings, so time is O(n). The Map holds at most one entry per distinct character, so space is O(k).

Save yourself the pain

Common mistakes

Oops

Sorting both strings and comparing, then calling it O(n).

Do this instead

Sorting costs O(n log n). It's a fine answer, just say the right complexity.

Oops

Using s.split('') on text with emoji and getting broken characters.

Do this instead

Use for...of or [...s], which loop over full characters instead of UTF-16 pieces.

Your mission

String trio

~30 min

Quick check

You check anagrams by sorting both strings and comparing them. What's the time complexity?

Go deeper

  1. 1Solve classic string problems: palindrome check, anagram check, longest substring.
  2. 2Learn common patterns: sliding window, character frequency maps.
  3. 3Practice both the brute-force and optimized solution for a few problems.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge