Arrays & Hashing · Pattern 25 of 26

String basics

Compare character by character, split into parts, and remember the classic tricks: a rotation of s is a substring of s + s, and length-prefix encoding survives any character.

3 variations · 7 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Common prefix, alternating patterns, version numbers
  • Is one string a rotation of another?
  • Encode a list of strings into one string and back

The template

String Basics
String longestCommonPrefix(String[] strs) {
    if (strs.length == 0) return "";
    for (int i = 0; i < strs[0].length(); i++) {
        char c = strs[0].charAt(i);
        for (String s : strs)
            if (i == s.length() || s.charAt(i) != c) return strs[0].substring(0, i);   // first mismatch
    }
    return strs[0];
}

The variations

  1. 1Compare character by character

    Scan column by column (common prefix), against an expected pattern (alternating), or part by part (version numbers).

  2. 2Rotations and encodings

    goal is a rotation of s exactly when lengths match and goal is inside s + s. Encode each string as "length#string" so any content decodes safely.

  3. 3More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Comparing version numbers as strings ("1.10" vs "1.9"): split and compare integers.
  • Encoding with a separator that can appear inside the strings: prefix each with its length instead.
Next: Sort first, then compare neighbours →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.