Lesson 120 of 296
Strings: building, counting characters
What you will learn
- Strings as arrays of characters
- The cost of building strings
- Counting characters with an array or a Map
- Valid Anagram
- Group Anagrams
On this page
Strings in algorithms
A string behaves like a read-only array of characters: s[i], s.length. Strings are immutable (Lesson 32), so every "change" creates a new string.
Building strings efficiently
function repeatSlow(word: string, times: number): string {
let result = "";
for (let i = 0; i < times; i++) result += word;
return result;
}In many languages, adding to a string in a loop copies the whole string each time: O(n²). Modern JavaScript engines optimise this well in simple cases, but the safe, widely understood pattern is to collect pieces in an array and join once:
function repeatFast(word: string, times: number): string {
const parts: string[] = [];
for (let i = 0; i < times; i++) parts.push(word);
return parts.join("");
}Mention this in interviews; it shows you know the cost of immutable strings.
Converting between strings and arrays
function reverseString(s: string): string {
return [...s].reverse().join("");
}[...s] splits into characters (and handles most emoji better than split("")).
Counting characters
Many string problems are about how many times each character appears.
With a Map (works for any characters):
function charCounts(s: string): Map<string, number> {
const counts = new Map<string, number>();
for (const ch of s) {
counts.set(ch, (counts.get(ch) ?? 0) + 1);
}
return counts;
}With a fixed array of 26 (only lowercase English letters; a little faster):
function letterCounts(s: string): number[] {
const counts = new Array<number>(26).fill(0);
for (const ch of s) {
const index = ch.charCodeAt(0) - 97;
counts[index] = counts[index]! + 1;
}
return counts;
}"a".charCodeAt(0) is 97, so "a" goes to index 0, "b" to 1, and so on.
Valid Anagram
Problem (LeetCode 242): are two strings anagrams (the same letters in a different order)? "listen" and "silent" are.
Approach 1: sort both and compare. O(n log n).
function isAnagramSort(s: string, t: string): boolean {
if (s.length !== t.length) return false;
return [...s].sort().join("") === [...t].sort().join("");
}Approach 2: count. Add 1 for each letter in s, subtract 1 for each in t. If every count ends at 0, they match. O(n) time.
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const counts = new Map<string, number>();
for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of t) {
const count = counts.get(ch);
if (!count) return false;
counts.set(ch, count - 1);
}
return true;
}Space: O(1) for a fixed alphabet (at most 26 letters), O(k) for k different characters in general.
Group Anagrams
Problem (LeetCode 49): group words that are anagrams of each other.["eat", "tea", "tan", "ate", "nat", "bat"] gives [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]].
Idea: anagrams share a signature. Use it as a Map key.
- Signature by sorting the letters:
"eat"→"aet". Cost O(k log k) per word of length k. - Signature by counting letters:
"1#0#0#...#1#...". Cost O(k) per word.
function groupAnagrams(words: string[]): string[][] {
const groups = new Map<string, string[]>();
for (const word of words) {
const key = [...word].sort().join("");
const group = groups.get(key);
if (group) group.push(word);
else groups.set(key, [word]);
}
return [...groups.values()];
}Time: O(n × k log k) for n words of length up to k. Space: O(n × k).
Counting-signature version for lowercase letters:
function groupAnagramsByCount(words: string[]): string[][] {
const groups = new Map<string, string[]>();
for (const word of words) {
const key = letterCounts(word).join("#");
const group = groups.get(key);
if (group) group.push(word);
else groups.set(key, [word]);
}
return [...groups.values()];
}The # separator matters: without it, counts like [1, 11] and [11, 1] could produce the same key.
Other common string patterns
| Pattern | Where |
|---|---|
| Two pointers from both ends | Valid Palindrome (Lesson 123) |
| Sliding window with counts | Longest Substring Without Repeating Characters (Lesson 126) |
| Stack | Valid Parentheses (Lesson 128) |
| Trie | Prefix search (Lesson 148) |
| Dynamic programming | Longest Common Subsequence, Word Break (Lesson 147) |
How to say it in an interview
"Strings are immutable, so I build results in an array and join once. Most string problems reduce to counting characters, with a Map in general or a 26-length array for lowercase letters. For Valid Anagram I count up for one string and down for the other, O(n). For Group Anagrams I use a Map from a canonical key, sorted letters or a count signature with separators, to the list of words."
Key words
| Word | Meaning |
|---|---|
| Anagram | A word made from the same letters in another order |
| Frequency count | How many times each item appears |
| Signature / canonical key | A standard form that equal items share |
| charCodeAt | The numeric code of a character |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.