Strings

How strings are stored, why building one with += in a loop is slow, how to count letters with 26 counters, and what interviewers ask about strings.

14 minLesson 2 of 6
On this page
  1. How a string is stored
  2. Why a string cannot be changed in place
  3. Building a string from parts
  4. Counting letters with 26 counters
  5. Cost of common string operations
  6. Variants of the counting technique
  7. Pitfalls when working with strings
  8. In the interview
  9. What to practise next

A string is a sequence of characters, stored like an array, and in JavaScript and Python it cannot be changed after it is created. Almost every text problem relies on two consequences of that: reading a character by index is cheap, and building a long string by repeated appending can be slow. This lesson covers both, plus the standard way to count letters when you need to compare words.

Without this knowledge, code that is correct and fast on a small test can become very slow on real input. A loop that does report += line for ten thousand lines copies the growing report on each step, so the running time grows with the square of the number of lines instead of with the number of lines.

How a string is stored

Underneath, a string is an array of characters stored side by side, so the array costs carry over. Reading s[3] is O(1), the length is stored so s.length and len(s) are O(1), and looping over every character is O(n).

Each character is stored as a number called its character code. The letters a to z have the codes 97 to 122 in order, so subtracting the code of a turns any lowercase letter into a position from 0 to 25. For example, c becomes 99 − 97 = 2. This is what makes the counting technique later on this page possible.

Why a string cannot be changed in place

Strings in JavaScript and Python are immutable, which means that once a string exists its characters never change. Assigning s[0] = "J" does nothing in JavaScript (or throws an error in strict mode) and raises an error in Python. Methods such as toUpperCase(), replace() and slicing return a new string and leave the original alone.

This is why report += line can be expensive. It may allocate a new string and copy the old report plus the new line into it. The first append copies one piece, the second copies two, and so on.

s += "A" A 1 copied s += "B" A B 2 copied s += "C" A B C 3 copied s += "D" A B C D 4 copied 10 in total
Each += may copy everything built so far, so four appends copy 1 + 2 + 3 + 4 = 10 characters.

For n pieces that adds up to 1 + 2 + … + n, which is about n²/2 copies, so the loop is O(n²). Ten thousand lines means around 50 million piece copies where ten thousand would be enough.

Building a string from parts

The fix is to append the pieces to an array, which grows cheaply, and join them once at the end. The join step adds up the total length first and then copies each piece exactly once, so the whole build is O(n).

function buildReport(sales) {
  const lines = [];
  for (const sale of sales) {
    lines.push(`${sale.item}: ${sale.amount}`); // cheap append to an array
  }
  return lines.join("\n"); // one copy of everything, at the end
}
 
buildReport([{ item: "tea", amount: 4 }, { item: "cake", amount: 7 }]);
// "tea: 4\ncake: 7"
def build_report(sales):
    lines = []
    for sale in sales:
        lines.append(f"{sale['item']}: {sale['amount']}")  # cheap append to a list
    return "\n".join(lines)  # one copy of everything, at the end
 
build_report([{"item": "tea", "amount": 4}, {"item": "cake", "amount": 7}])
# "tea: 4\ncake: 7"

Modern JavaScript engines, and CPython in simple cases, can often avoid the full copy when you use +=. You cannot rely on that, and an interviewer will expect you to know the join approach, so use it for any loop that builds a long string.

Counting letters with 26 counters

Many string problems ask which characters appear in a string and how often. The standard example is the anagram check: two words are anagrams when they contain exactly the same letters the same number of times, so tea and eat are anagrams while tea and tee are not.

When the words contain only lowercase letters, keep an array of 26 counters, one for each letter. Add 1 to a letter's counter for every letter of the first word, and subtract 1 for every letter of the second word. If the words are anagrams, every counter ends at 0. The tracer shows only the counters for a, e and t, because the other 23 stay at 0.

Are tea and eat anagrams?Use the arrows or ← → keys
if lengths differ: return falsecounts = 26 zerosfor ch in first: counts[ch - 'a'] += 1for ch in second: counts[ch - 'a'] -= 1return every count is 0
  1. first
    0t
    1e
    2a
    counts
    aet
    000

    1Both words have 3 letters, so the length check passes. All counters start at 0.

  2. first
    0tch
    1e
    2a
    counts
    aet
    001

    2The code of t is 116, and 116 − 97 = 19, so t uses counter 19. Add 1 to it.

  3. first
    0t
    1ech
    2a
    counts
    aet
    011

    3The letter e adds 1 to its counter.

  4. first
    0t
    1e
    2ach
    counts
    aet
    111

    4The letter a adds 1 to its counter. The counters now describe the first word.

  5. second
    0ech
    1a
    2t
    counts
    aet
    101

    5Now the second word subtracts. The letter e takes the e counter back to 0.

  6. second
    0e
    1ach
    2t
    counts
    aet
    001

    6The letter a subtracts 1 from its counter.

  7. second
    0e
    1a
    2tch
    counts
    aet
    000

    7The letter t subtracts 1 from its counter.

  8. second
    0e
    1a
    2t
    counts
    aet
    000
    result
    true

    8Every counter is 0, so the words are anagrams. The work was 6 letter visits plus 26 counter checks.

1 / 8

With tea and tee the same procedure ends with the a counter at 1 and the e counter at −1, so the words are not anagrams.

// Assumes both words use only lowercase a to z.
function isAnagram(first, second) {
  if (first.length !== second.length) return false;
  const counts = new Array(26).fill(0);
  const A = "a".charCodeAt(0); // 97
  for (const ch of first) counts[ch.charCodeAt(0) - A]++;
  for (const ch of second) counts[ch.charCodeAt(0) - A]--;
  return counts.every((c) => c === 0);
}
 
isAnagram("tea", "eat"); // true
isAnagram("tea", "tee"); // false
# Assumes both words use only lowercase a to z.
def is_anagram(first, second):
    if len(first) != len(second):
        return False
    counts = [0] * 26
    for ch in first:
        counts[ord(ch) - ord("a")] += 1
    for ch in second:
        counts[ord(ch) - ord("a")] -= 1
    return all(c == 0 for c in counts)
 
is_anagram("tea", "eat")  # True
is_anagram("tea", "tee")  # False

Cost of common string operations

ApproachTimeSpaceWhy
Read s[i] or the lengthO(1)O(1)Reading by index costs the same as in an array.
Compare, copy or sliceO(n)O(n) for a copyThese operations look at every character.
+= in a loop of n piecesO(n²)O(n)Each step can copy everything built so far.
Collect parts, join onceO(n)O(n)Each character is copied only once.
Anagram check with 26 countersO(n)O(1)There are 26 counters no matter how long the words are.

Variants of the counting technique

Counters for a larger alphabet

The 26-counter array assumes lowercase a to z. If the input can contain uppercase letters, digits or punctuation, either lowercase and clean the input first, or use a hash map from character to count (Map in JavaScript, collections.Counter in Python). The hash map handles any character at the same O(n) time, and its space is proportional to the number of distinct characters. Use the array when the problem promises lowercase letters, because it is simpler and slightly faster, and use the hash map otherwise. See hash tables.

Comparing sorted strings

Two words are anagrams exactly when their sorted letters are equal, so sorted(first) == sorted(second) is a correct one-line answer. It costs O(n log n) because of the sort, against O(n) for counting. It is a fine first answer in an interview, and the counting version is the improvement to offer next. Sorting is also the easy way to build a grouping key when the task is to put anagrams into groups: all words with the same sorted letters belong together.

Other problems that use counts

The same counters answer several common questions. To find the first character that appears only once, count every character in one pass and then scan the string again, returning the first character whose count is 1. To check whether a ransom note can be written from a magazine, count the magazine letters and subtract the note letters, and fail if any counter goes below 0. To check whether a string can be rearranged into a palindrome, count the characters and allow at most one character with an odd count.

Checking a string from both ends

Counting tells you what a string contains but not the order of its characters. Problems about order, such as palindromes, call for two indexes that start at the two ends and move toward each other, which is covered in two pointers. A related case is a window of characters that moves along the string, which is the subject of sliding window.

When counting does not apply

Counters ignore position, so they cannot answer questions such as whether one string appears inside another. That is substring search, covered in string matching. Questions about many words that share prefixes are better served by a trie.

Pitfalls when working with strings

In the interview

A problem is probably a string-counting problem when it asks whether two strings use the same characters, whether one can be rearranged into another, which character is the first unique one or the most frequent one, or whether a string can be rearranged into a palindrome. Mention the character set and ask about it: "Are the strings lowercase letters only?" The answer decides between 26 counters and a hash map. Also ask whether case and spaces matter.

Questions to expect:

  • "Why is building a string with += in a loop slow?" Strings are immutable, so each append may copy everything built so far, which adds up to O(n²). Collect the pieces in a list and join once for O(n). Add that some runtimes optimise simple cases, but you should not depend on it.
  • "What is the time and space of your anagram check?" Time is O(n), because each word is read once. Space is O(1), because there are 26 counters regardless of word length. If you used a hash map instead, space is O(k) where k is the number of distinct characters.
  • "What if the strings can contain any Unicode text?" Switch from the array to a hash map keyed by character, and note that a user-perceived character can be several code points, so the exact definition of a character has to be agreed on. For an interview, state the assumption and move on.
  • "Can you avoid the extra space?" Sorting both strings in place needs no counters, but it costs O(n log n) time, and in JavaScript and Python strings cannot be sorted in place anyway, so you first copy them into arrays. Counting is the better trade for most inputs.
  • "How would you group a list of words into anagram groups?" Give every word a key that is the same for anagrams, either its sorted letters or a tuple of its 26 counts, and store the words in a hash map from key to list. Sorting each word costs O(k log k) for a word of length k, and building the count key costs O(k).
  • "What does comparing two strings cost?" Equality checks are O(n) in the worst case, because they may compare every character. This matters when you compare strings inside loops or use them as hash map keys, since computing the hash of a string reads all of it, although some runtimes cache the result.
Quick check

A loop runs n times and does result += piece each time, where every piece is short. If each += copies the whole string, what is the total cost?

You run the counter check on "cab" and "dab". Which counters are not 0 at the end?

Why is the 26-counter anagram check O(1) in space, even for very long words?

An interviewer says the input may contain uppercase letters, digits and punctuation. What is the best change to the anagram check?

What to practise next

The 26 counters work only because the alphabet is small and known. For arbitrary keys you need a hash table, and for finding one string inside another you need string matching.