Lesson 3 · Linear structures

Strings and Substring Algorithms

A string is an array of characters, or more exactly of code units in some encoding. Most languages make strings immutable, so every edit builds a new one. Knowing where those copies hide, what a substring is, and the two shapes most string problems take covers most everyday string work.

Strings and Substring Algorithms concept diagramA visual explanation of the layout and operations shown in this lesson.Hidx 0Eidx 1Lidx 2Lidx 3Oidx 4a string is an array of characters, addressed by indexs[1:4] = "ELL" — a substring is a contiguous slice"LEO" shares the same letters but is not a substring: order and adjacency both matter
1

What a String Actually Holds

A string is a sequence of characters. As a string data structure it is an array underneath: the characters sit in consecutive slots and any one of them is read by index in O(1). The more exact definition matters, though: the slots hold code units in some encoding, and the gap between code units and visible characters is where a large class of bugs lives.

In ASCII, one byte is one character and length counts characters. In UTF-8, a code point takes one to four bytes, so 5 visible characters may take 10 bytes. In UTF-16, used inside Java, JavaScript and C#, most characters are one 16-bit unit, but emoji and rarer scripts take two, called a surrogate pair.

The consequences are concrete. "😀".length is 2 in JavaScript and Java and len("😀") is 1 in Python 3, which indexes by code point. Reversing a UTF-16 string unit by unit splits surrogate pairs and produces invalid text. Even code points are not the end of it: a base letter plus a combining accent is two code points that display as one character.

Practice problems almost always assume ASCII or lowercase letters. Say so out loud ('assuming lowercase a to z') rather than assuming it silently; it is one sentence and it shows you know the general case.

Storage differs by language too. C keeps a null terminated string: an array of bytes ending in a '\0' byte, with no stored length. strlen therefore scans to the terminator in O(n), and a missing terminator lets code read past the buffer, a classic source of overflows. Most other languages store the length next to the characters, so asking for it is O(1) and the string can contain zero bytes safely.

  • len("😀".encode("utf-8")) is 4: one code point, four bytes
  • é can be one code point (U+00E9) or two (e + U+0301); normalise both strings (NFC) before comparing them
  • A C buffer for a 5-character string needs 6 bytes, the last one for '\0'
2

Immutability and the Quadratic Trap

Java, Python, C# and JavaScript all use immutable strings: no operation changes an existing string; each one returns a new string. That buys real advantages. A string can be shared without defensive copies, its hash can be computed once and cached, and it is safe as a map key and across threads.

It also causes the most common performance bug in string code. Building a string with repeated result += piece looks linear and is not. Each += allocates a new string and copies everything accumulated so far, so n one-character appends copy 1 + 2 + … + n characters, which is O(n²). For 1,000 pieces that is about half a million character copies; for 100,000 it is about five billion, and the program seems to hang.

The fix is to collect into a mutable buffer and convert once at the end: StringBuilder in Java and C#, a list of pieces and one "".join(...) in Python, an array and join in JavaScript. A builder appends into spare capacity and doubles it when full, so n appends cost O(n) in total.

The trap survives testing because small inputs are fast either way. CPython makes it worse by sometimes resizing in place when += holds the only reference to the string: the loop runs fine in a script and then falls back to copying in other interpreters or once a second reference exists.

Slicing costs too. A substring in Java or Python is a new string, so taking one copies its k characters. A recursive function that slices on every call can be quadratic without any concatenation, which is why recursive string code passes start and end indices instead of substrings.

Where the cost hides in string operations
OperationCostNote
Index a characterO(1)O(n) if the encoding is variable-width
Concatenate two stringsO(n + m)A new allocation every time
Build in a loop with +=O(n²)The classic trap
Build with a builder or joinO(n)Always prefer this
Slice a substringO(k)Pass index ranges instead
Compare two stringsO(n)Length check first — often O(1)
  • C++ std::string is mutable: s += c appends in place, amortised O(1), so the loop pattern is fine there
  • Java turns a + b + c inside one expression into a single builder, but not appends spread across loop iterations
  • To edit characters in place, convert first: list(s) in Python, s.toCharArray() in Java
3

Substrings, Prefixes and Suffixes

A substring is a contiguous run of characters, s[i:j]. In HELLO, ELL is a substring and LEO is not, even though it uses the same letters: order and adjacency both count. A prefix is a substring that starts at index 0 and a suffix is one that runs to the end. A string of length n has n prefixes, n suffixes and n(n+1)/2 substrings counted by position (15 for HELLO).

Substring vs subsequence is the distinction to check first in any problem statement. A subsequence keeps the order but may skip characters: ace is a subsequence of abcde but not a substring. There are about n²/2 substrings but 2ⁿ subsequences, which is why substring questions usually fall to a scan or a window while subsequence questions usually need dynamic programming. String manipulation techniques covers both families.

The central substring question is search: where does a pattern of length m occur in a text of length n? The direct method tries every start position and compares up to m characters there, O(n·m) in the worst case. Searching aaab in aaaaaaaa shows why: every start matches three characters before it fails.

The faster methods avoid re-reading characters. KMP precomputes, for each prefix of the pattern, how far it can shift after a mismatch, giving O(n + m). The Z algorithm reaches the same bound through prefix-match lengths, and Rabin–Karp compares rolling hashes first and characters only on a hash match, O(n + m) expected.

When the text is fixed and searched many times, it pays to index the text instead of the pattern. Every substring is a prefix of some suffix, so sorting the suffixes (suffix arrays) or storing them in one tree (suffix trees) answers each search in time that hardly depends on n.

Key reference

Terms, operations, and practical uses

Core vocabulary

  • Character EncodingA standard (like ASCII or UTF-8) that assigns numerical values to characters so they can be stored in memory.
  • ImmutabilityA property where an object's state cannot be modified after it is created. Any 'modification' actually returns a new object.
  • SubstringA contiguous sequence of characters within a string (e.g., 'ell' is a substring of 'hello').

Algorithms

  • KMP AlgorithmPrecomputes how far the pattern can shift after a mismatch, so no text character is read twice; O(n + m) to find a pattern of length m in a text of length n.
  • Rabin-KarpCompares a rolling hash of each text window with the pattern's hash, and checks characters only when the hashes match; O(n + m) expected.
  • Two PointersOne index at each end moving inward, as in a palindrome check; O(n) time and O(1) space.

Best practices

  • String BuildersA mutable buffer (StringBuilder, or a list joined once) that appends into spare capacity, so n appends cost O(n) in total.
  • Character ArraysConverting an immutable string into an array of characters (e.g., list(str)) to perform in-place modifications.
  • O(1) Length CheckMost modern languages store the length of the string as a property, making len(str) an O(1) operation.
Implementation

Code in Python, C++ and Java

def is_palindrome(s):
    left, right = 0, len(s) - 1
    comparisons = 0
    while left < right:
        comparisons += 1
        if s[left] != s[right]:
            return False, comparisons
        left += 1
        right -= 1
    return True, comparisons

def is_anagram(a, b):
    if len(a) != len(b):
        return False
    counts = [0] * 26                    # assumes lowercase a-z
    for ch in a:
        counts[ord(ch) - ord('a')] += 1
    for ch in b:
        i = ord(ch) - ord('a')
        if counts[i] == 0:
            return False
        counts[i] -= 1
    return True

for word in ['racecar', 'racecat']:
    ok, steps = is_palindrome(word)
    print(f"{word}: palindrome {ok}, comparisons {steps}")

for a, b in [('listen', 'silent'), ('rat', 'car'), ('abc', 'ab')]:
    print(f"{a} / {b}: anagram {is_anagram(a, b)}")
#include <iostream>
#include <string>
using namespace std;

bool isPalindrome(const string& s, int& comparisons) {
    int left = 0, right = (int)s.size() - 1;
    comparisons = 0;
    while (left < right) {
        comparisons++;
        if (s[left] != s[right]) return false;
        left++;
        right--;
    }
    return true;
}

bool isAnagram(const string& a, const string& b) {
    if (a.size() != b.size()) return false;
    int counts[26] = {0};                // assumes lowercase a-z
    for (char ch : a) counts[ch - 'a']++;
    for (char ch : b) {
        if (counts[ch - 'a'] == 0) return false;
        counts[ch - 'a']--;
    }
    return true;
}

int main() {
    for (string word : {"racecar", "racecat"}) {
        int steps = 0;
        bool ok = isPalindrome(word, steps);
        cout << word << ": palindrome " << (ok ? "True" : "False")
             << ", comparisons " << steps << "\n";
    }
    string pairs[3][2] = {{"listen", "silent"}, {"rat", "car"}, {"abc", "ab"}};
    for (auto& p : pairs)
        cout << p[0] << " / " << p[1] << ": anagram "
             << (isAnagram(p[0], p[1]) ? "True" : "False") << '\n';
}
class Main {
    static int comparisons = 0;

    static boolean isPalindrome(String s) {
        int left = 0, right = s.length() - 1;
        comparisons = 0;
        while (left < right) {
            comparisons++;
            if (s.charAt(left) != s.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }

    static boolean isAnagram(String a, String b) {
        if (a.length() != b.length()) return false;
        int[] counts = new int[26];          // assumes lowercase a-z
        for (char ch : a.toCharArray()) counts[ch - 'a']++;
        for (char ch : b.toCharArray()) {
            if (counts[ch - 'a'] == 0) return false;
            counts[ch - 'a']--;
        }
        return true;
    }

    static String py(boolean b) { return b ? "True" : "False"; }

    public static void main(String[] args) {
        for (String word : new String[] {"racecar", "racecat"}) {
            boolean ok = isPalindrome(word);
            System.out.println(word + ": palindrome " + py(ok) + ", comparisons " + comparisons);
        }
        String[][] pairs = {{"listen", "silent"}, {"rat", "car"}, {"abc", "ab"}};
        for (String[] p : pairs)
            System.out.println(p[0] + " / " + p[1] + ": anagram " + py(isAnagram(p[0], p[1])));
    }
}
Watch it run

Step through it

Running on "racecar", "racecat", then "listen" / "silent", "rat" / "car", "abc" / "ab"

s = "racecar"comparisons 0r0a1c2e3c4a5r6LRL starts at the first index, R at the last
Step 1

A string is an array of characters

'racecar' is seven characters at indices 0 to 6. Reading any one of them by index is O(1), which is what lets two pointers jump straight to both ends without walking there.

Output
1 / 12
4

Two Pointers and Counting

Most interview string problems take one of two shapes. When the order of characters matters, two indices move through the string. When only which characters appear and how often matters, a count table replaces comparison.

Palindromes are the two-pointer case, as the tracer above shows. Start one index at each end, compare, and step inward; a mismatch ends the check, and pointers meeting or crossing means every pair matched. That is O(n) time and O(1) space, and it can stop after the first comparison, while comparing a string with its reverse always builds a full copy first. When the problem says to ignore case and punctuation, skip those characters inside the pointer loop rather than building a cleaned copy.

The same pointers run outward for the longest palindromic substring: expand from each of the 2n − 1 centres (every character and every gap, so even lengths are found too), O(n²) overall. Forgetting the gap centres is the usual bug. Manacher's algorithm does it in O(n).

Anagrams are the counting case. Reject unequal lengths first, count the letters of one string, then count down with the other; a count that is already 0 means the strings differ. That is O(n), against O(n log n) for sorting both. For a known small alphabet, a fixed 26-cell array beats a hash map: no hashing, no allocation, and the index is just c - 'a'.

The count vector also works as a key: words with the same counts are anagrams of each other, so one pass with a hash map groups them. Combined with a sliding window, the same counts find every anagram of a pattern inside a longer text, adding one character and removing one per step.