Skip to lesson

Practice: string algorithms

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

In this comprehensive string algorithms practice lesson, we synthesize all pattern matching techniques. We examine decision frameworks for picking the ideal algorithm and solve classic interview challenges.

Decision Framework: Selecting the Right String Algorithm

When approaching a string problem in an interview, how do you choose among KMP, the Z-algorithm, rolling hashes, and expand-around-centre? Start by classifying the problem requirement.

Example 1 · Algorithm Selection Benchmark

StringAlgorithmChooserDemo.javaJava
public class StringAlgorithmChooserDemo {    public static String chooseAlgorithm(String problemType) {        switch (problemType) {            case "STREAM_SEARCH": return "KMP (no text backtracking)";            case "MULTI_PATTERN": return "Aho-Corasick or Rabin-Karp";            case "LONGEST_PALINDROME": return "Manacher or Expand-Around-Center";            case "COMPETITIVE_MATCH": return "Z-algorithm (fast concatenation)";            default: return "Built-in indexOf";        }    }
    public static void main(String[] args) {        System.out.println(chooseAlgorithm("STREAM_SEARCH"));        System.out.println(chooseAlgorithm("LONGEST_PALINDROME"));    }}
Output
KMP (no text backtracking)
Manacher or Expand-Around-Center

What this code does

  • Maps string problem requirements to ideal algorithmic paradigms.
  • Emphasizes streaming versus competitive vs multi-pattern considerations.
  • Guides clean architectural choices in interview settings.

If you need exact single-pattern search on character streams without storing full text in memory, choose KMP. If the problem asks for prefix-suffix properties, periodic repeating blocks, or shortest palindromes, KMP's LPS array is uniquely suited. If you need substring matching with clean code in competitive programming, the Z-algorithm with concatenation is fastest to write. If you need multi-pattern matching, 2D matrix search, or duplicate substring search with binary search, polynomial rolling hashes (Rabin-Karp) are ideal.

Repeated String Matching: Cycle Expansion

In Repeated String Match, we want the minimum repetitions of string A so that string B is a substring of the repeated string. A naive loop appending A indefinitely wastes memory and risks infinite looping.

Example 2 · Repeated String Match Solver

RepeatedStringMatchDemo.javaJava
public class RepeatedStringMatchDemo {    public static int repeatedStringMatch(String a, String b) {        StringBuilder sb = new StringBuilder(a);        int count = 1;
        while (sb.length() < b.length()) {            sb.append(a);            count++;        }
        if (sb.indexOf(b) != -1) return count;        if (sb.append(a).indexOf(b) != -1) return count + 1;
        return -1;    }
    public static void main(String[] args) {        System.out.println("Reps for 'abcd' and 'cdabcdab': " + repeatedStringMatch("abcd", "cdabcdab"));        System.out.println("Reps for 'a' and 'aa': " + repeatedStringMatch("a", "aa"));    }}
Output
Reps for 'abcd' and 'cdabcdab': 3
Reps for 'a' and 'aa': 2

What this code does

  • Repeats string a until its length is at least b.length().
  • Tests count repetitions, then at most count + 1 repetitions to handle boundary wraps.
  • Returns -1 if b is still absent, bounding work to O(N + M) time.

Notice the mathematical bound: for B to appear inside repeated A, the repeated string must have length at least |B|. In fact, repeating A until its length is >= |B| gives candidate repetitions k = ceil(|B| / |A|). If B is not found in k repetitions of A, it can at most appear in k + 1 repetitions (spanning across boundary wraps). If B is absent in k + 1 repetitions, it can never appear, allowing KMP or indexOf to resolve the problem in O(|A| * k) time.

Longest Happy Prefix: Pure LPS Application

A 'happy prefix' is a non-empty prefix that is also a suffix, excluding the string itself. Finding the longest happy prefix is the exact mathematical definition of the final entry in the KMP failure table: lps[N - 1].

Example 3 · Longest Happy Prefix via KMP LPS

LongestHappyPrefixDemo.javaJava
public class LongestHappyPrefixDemo {    public static String longestPrefix(String s) {        int n = s.length();        int[] lps = new int[n];        int len = 0, i = 1;
        while (i < n) {            if (s.charAt(i) == s.charAt(len)) {                lps[i++] = ++len;            } else {                if (len > 0) len = lps[len - 1];                else lps[i++] = 0;            }        }        return s.substring(0, lps[n - 1]);    }
    public static void main(String[] args) {        System.out.println("Happy prefix for 'level': '" + longestPrefix("level") + "'");        System.out.println("Happy prefix for 'ababab': '" + longestPrefix("ababab") + "'");    }}
Output
Happy prefix for 'level': 'l'
Happy prefix for 'ababab': 'abab'

What this code does

  • Constructs the LPS array across the entire string in O(N) time.
  • lps[n - 1] contains the exact length of the longest prefix-suffix.
  • Extracts 'l' for 'level' and 'abab' for 'ababab'.

While naive checking compares all N - 1 prefix-suffix pairs in O(N^2) time, building the KMP LPS array takes strictly O(N) time and O(N) space. Extracting S.substring(0, lps[N - 1]) yields the longest happy prefix in a single linear pass, showcasing how foundational string theory translates directly into one-line solutions.

Handling Memory and Large Alphabet Constraints

In high-throughput systems, string algorithm efficiency depends heavily on memory layout and character set assumptions.

When alphabet size is small (e.g. DNA alphabet with 4 characters 'A', 'C', 'G', 'T'), algorithms can precompute full finite automaton transitions in O(|P| * |Sigma|) time, allowing each text character to be processed in strictly 1 state transition.

For large Unicode alphabets, avoid allocating fixed 256 or 65536 array tables per state. Prefer pointer-based LPS arrays or hash maps to keep auxiliary space proportional to pattern length rather than alphabet capacity.

Finish up

Mark complete & continue

Next: The range query problem