Strings

How text is stored, why strings are often immutable, and the techniques behind every string problem.

Beginner 3 min readLesson 2 of 16 Interview Q&A

A string is a sequence of characters. Under the hood it is almost always an array of code units (bytes or 16-bit chars) plus a length. Everything you know about arrays applies — O(1) indexing, O(n) search — with two twists: encoding and immutability.

h0e1l2l3o4
"hello" stored as an array of characters

Encoding: characters are numbers

Computers store numbers, so each character is mapped to a number (a code point) and then encoded into bytes. See Data Representation for the full story.

LanguageInternal representation"héllo".length
JavaUTF-16 (compact Latin-1 when possible)5
JavaScriptUTF-16 code units5
Python 3Code points (flexible 1/2/4-byte storage)5
Rust / GoUTF-8 bytes6 bytes

Immutability

In Java, Python, JavaScript, C# and Go, strings are immutable: every "modification" creates a new string. Benefits: safe to share between threads, safe as hash-map keys, hash code can be cached, and literals can be interned (deduplicated).

The cost: building a string with += in a loop copies the whole string every time — O(n²) total.

// ✗ O(n²): each += copies the entire string so far
String s = "";
for (int i = 0; i < n; i++) s += i;

// ✓ O(n): StringBuilder is a mutable, growable char array
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) sb.append(i);
String result = sb.toString();

Essential operations

OperationTypical costNotes
s[i] / charAt(i)O(1)
lengthO(1)Stored, not computed (except C's strlen: O(n))
Concatenate a + bO(len a + len b)New string
Substring / sliceO(k)Copies k chars
indexOf(pattern)O(n·m) worstNaive; KMP is O(n+m)
Compare a.equals(b)O(min length)Use equals, never ==, in Java

Core techniques

Frequency counting

Anagrams, permutations, "first unique character" — count characters in a fixed-size array (26 for lowercase letters) or a hash map.

boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) {
        count[s.charAt(i) - 'a']++;
        count[t.charAt(i) - 'a']--;
    }
    for (int c : count) if (c != 0) return false;
    return true;
}

Two pointers from both ends

Palindromes and reversals: compare s[l] with s[r], move inward.

boolean isPalindrome(String s) {
    int l = 0, r = s.length() - 1;
    while (l < r) {
        while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
        while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
        if (Character.toLowerCase(s.charAt(l++)) != Character.toLowerCase(s.charAt(r--))) return false;
    }
    return true;
}

Other go-to tools

  • Sliding window for "longest/shortest substring with property X" → Sliding Window.
  • Hashing / rolling hash for substring matching → Rabin–Karp.
  • Tries for prefix queries over many words → Tries.
  • DP for edit distance, LCS, palindromic subsequences → DP on sequences.
Key takeaways
  • A string is an array of encoded characters; know whether your language counts bytes, UTF-16 units or code points.
  • Immutable strings are safe and hashable, but repeated += can be O(n²) — use a builder / join.
  • Most string problems reduce to counting, two pointers, sliding window, hashing, tries or DP.
Interview questions
QWhy are strings immutable in Java?easy

Security (a validated filename/URL can't change afterwards), thread safety without locks, a cacheable hashCode (great for HashMap keys), and the string pool: identical literals can share one object only if nobody can mutate it.

QWhat's the difference between == and equals() for Java strings?easy

== compares references (same object?), equals() compares contents. Two equal literals may be == because of interning, but strings built at runtime usually aren't. Always use equals.

QFind the first non-repeating character in a string.easy

Two passes: count frequencies (array of 26 or a map), then scan the string again and return the first char with count 1. O(n) time, O(1) space for a fixed alphabet.

QGroup a list of words into anagram groups.medium

Use a hash map whose key is a canonical form: the sorted word (O(k log k)) or a 26-length count tuple (O(k)). Append each word to its key's list. Total O(n·k).