Strings
A sequence of characters, and how to work with them efficiently.
What is it?
A string is a sequence of characters, like "hello". It stores text: a username, a message, a file's contents.
A string behaves a lot like an array of characters. Many classic coding problems are about processing strings efficiently: reversing them, searching within them, or checking how two strings relate.
Explain like I'm 10
A string is like a train where each car carries one letter. You can look at any car by its position, but checking whether it 'matches' another train means looking at the whole train. You also can't repaint one car: any 'edit' builds a brand new train, car by car.
Examples
Treating a string like an array of characters
const word = "hello";
console.log(word[0]); // "h"
console.log(word.length); // 5
const reversed = word.split("").reverse().join("");
console.log(reversed); // "olleh"split("") breaks the string into characters, .reverse() flips their order, and .join("") glues them back together.
How it works
JavaScript strings are immutable: once created, their contents never change. Anything that seems to "modify" a string (like .toUpperCase() or concatenation) returns a new string and leaves the original alone.
Why does it exist?
Text is everywhere: usernames, messages, file contents, search queries. Efficient string handling underpins search engines, spell checkers, text editors and almost every user-facing app.
When to use it
Think in string terms (immutability, character-by-character processing) when you validate text, search within it, or compare two texts, for example to check for anagrams or palindromes.
When not to use it
Building a huge string piece by piece in a loop with concatenation can be slow. Collecting the pieces in an array and joining once at the end is usually faster.
Common mistakes
Changing a character directly (e.g.
str[0] = "H"). Strings are immutable, so this silently does nothing.Concatenating strings in a large loop instead of building an array and joining it once at the end.
Forgetting that string comparison (
===) is case-sensitive.
Practice exercises
- Easy:
Write a function that checks if a string is a palindrome (reads the same forwards and backwards).
- Medium:
Write a function that counts how many times each character appears in a string.
- Hard:
Write a function that checks if two strings are anagrams (the same letters, in any order).
Interview questions
Are strings mutable in JavaScript?
No, strings are immutable. Any method that seems to change a string returns a new one.
How would you check if a string is a palindrome?
Compare it to its reverse, or move two pointers from both ends toward the middle and check that the characters match at each step.
What's an efficient way to count character frequency in a string?
In one pass, use a hash table (or plain object) that maps each character to a running count.
Why is building up a large string with `+=` inside a loop inefficient?
Strings are immutable, so each += builds a new string by copying the old characters plus the new piece. If the string grows by one piece per iteration, total copying over n iterations is about 1 + 2 + ... + n: O(n²), not O(n).
What's a more efficient way to build a large string piece by piece, and why?
Push each piece into an array, then call .join("") once. Each push is amortized O(1), so filling the array is O(n), and .join is one O(n) pass. That avoids recopying the whole string on every +=.
What's the time complexity of reading a character by index, like `str[3]`?
O(1). As with an array, the position is calculated directly, without scanning earlier characters.
What's the time complexity of comparing two strings for equality with `===`, and why?
O(n) worst case, where n is the string length. Characters are compared one by one until a mismatch or the end, so identical strings (or ones differing only at the end) need nearly every character checked.
If string equality is O(n) worst case, why does comparing two very different strings often feel instant in practice?
Comparison stops at the first mismatch. If two strings differ at position 2, only 3 comparisons are needed, however long they are. The O(n) worst case applies only when strings are identical or differ near the end.
What's the time complexity of a naive substring search, like `str.includes(sub)`?
O(n × m) worst case, where n is the main string's length and m the substring's. For each of about n starting positions, up to m characters may be compared.
How does a two-pointer approach check whether a string is a palindrome, and what's its time and space complexity?
One pointer starts at each end. They compare characters and move inward, stopping at the first mismatch. O(n) time (at most n/2 comparisons) and O(1) extra space, since it only needs two indices.
Both reversing a string and using two pointers can check for a palindrome in O(n) time — which uses less memory, and why?
Two pointers use O(1) extra space: just two indices. Reversing first (e.g. str.split("").reverse().join("")) builds a new string: O(n) extra space.
What are two ways to check if two strings are anagrams, and what's the time complexity of each?
Sort both strings' characters and compare: O(n log n), dominated by the sort. Or count character frequencies in a hash map for both and compare: O(n). Counting is faster; sorting is often simpler to write.
Why is checking that two strings have equal length a useful first step before checking if they're anagrams?
Strings of different lengths can't have the same characters. The O(1) length check rules out many pairs before any costly counting or sorting.
What does `"abc".repeat(3)` return, and what's the time complexity of `.repeat(k)`?
"abcabcabc". It's O(n × k), where n is the original length, since those n characters are copied k times.
What does `"hello".slice(-3)` return?
"llo". A negative argument counts back from the end, so -3 starts 3 characters before the end, and with no end argument it runs to the end.
Does `.length` always give the correct number of visible characters in a string?
Not always. .length counts UTF-16 code units, not visible characters. Many emoji and other characters outside the Basic Multilingual Plane are a surrogate pair of two code units, so a single emoji can report .length === 2. Code that assumes one unit per character can silently break.
Why can `str.split("").reverse().join("")` corrupt a string that contains certain emoji?
split("") splits by UTF-16 code unit, which can cut a surrogate-pair emoji in half. Reversing then swaps the two halves, producing garbled or invalid characters.
Why does `"Hello" === "hello"` evaluate to `false`, and how would you compare them case-insensitively?
Comparison is case-sensitive: uppercase and lowercase letters have different character codes. Call .toLowerCase() (or .toUpperCase()) on both sides first, at the cost of an extra O(n) pass for each copy.
If you need to check thousands of words against a large, fixed dictionary, why convert the dictionary array to a `Set` first?
dictionaryArray.includes(word) is O(n) per check, where n is the dictionary size (and each string comparison costs up to O(m), the word's length). Building a Set costs O(n) once, then each lookup is O(m) on average, independent of dictionary size. That's a big win over many lookups.
What's the time complexity of finding the longest substring without repeating characters, using brute force versus a sliding window?
Brute force checks every substring, and there are O(n²) of them, so it's at least O(n²) (worse, depending on how uniqueness is checked). A sliding window with a hash set of characters in view is O(n): each character is added and removed at most once, and each end of the window moves forward at most n times.
Why do string algorithms often favor tracking positions with pointers/indices rather than building new strings inside a loop?
Strings are immutable, so every "change" allocates and copies a new string. Slicing or concatenating in a loop repeats that copying each time. Tracking index positions in the original string avoids allocation until you build the final result.
What's the time complexity of converting a number to a string, or a string to a number?
O(d), where d is the number of digits or characters, since each is read or written individually. For fixed-size numbers it's often treated as O(1) in practice, but formally it scales with the digit count.
A candidate writes `str[0] = "H"` expecting to capitalize the first letter, but the string doesn't change. Why?
Strings are immutable, so assigning to an index silently does nothing (no error, no effect). Build a new string instead, e.g. "H" + str.slice(1).
Checking a palindrome with two pointers versus with recursion (comparing outer characters and recursing inward) are both O(n) time — do they use the same space?
No. The iterative two-pointer version uses O(1) extra space. The recursive version uses O(n), because it goes about n/2 calls deep and each call adds a stack frame. Recursion trades memory for shorter code.
Why is even just listing every substring of a string an O(n²) operation, before doing any work on them?
A string of length n has n(n+1)/2 contiguous substrings, one per start-and-end choice. That count grows quadratically, so just listing them is O(n²).
When counting character frequency with a hash map, is the space complexity always proportional to the string's length?
No. It's O(k), where k is the number of distinct characters. For a small fixed alphabet (like lowercase English letters, at most 26), that's effectively constant, however long the string.
Why might you convert a string into an array of characters before doing heavy processing on it, rather than working with the string directly?
Rebuilding an immutable string in a loop copies memory every time. Converting to an array once (O(n)) lets you read and overwrite elements in place, then .join("") once at the end (O(n)), with no repeated copying in between.
`Array.from(str)` and `str.split("")` both convert a string to an array of characters — do they behave the same way on strings containing emoji?
Not always, though both are O(n) time and space. Array.from (and spread, [...str]) iterate by Unicode code point, keeping a surrogate-pair emoji as one entry. split("") splits by UTF-16 code unit and can break the emoji into two invalid entries. The arrays can end up with different lengths.
Why is `str.trim()` O(n) rather than O(1), even when it only removes a couple of whitespace characters?
It scans inward from both ends to find where the whitespace stops, which can touch every character when there's none to remove. Then it builds a new string (strings are immutable) by copying the rest. Both steps scale with the string's length.