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.
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 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];
} def longest_common_prefix(strs):
if not strs:
return ""
for i, c in enumerate(strs[0]):
for s in strs:
if i == len(s) or s[i] != c:
return strs[0][:i] # first mismatch
return strs[0] string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
for (size_t i = 0; i < strs[0].size(); i++) {
char c = strs[0][i];
for (auto& s : strs)
if (i == s.size() || s[i] != c) return strs[0].substr(0, i); // first mismatch
}
return strs[0];
} function longestCommonPrefix(strs) {
if (strs.length === 0) return "";
for (let i = 0; i < strs[0].length; i++) {
const c = strs[0][i];
for (const s of strs)
if (i === s.length || s[i] !== c) return strs[0].slice(0, i); // first mismatch
}
return strs[0];
} The variations
-
1Compare character by character
Scan column by column (common prefix), against an expected pattern (alternating), or part by part (version numbers).
Now you solve -
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.
Now you solve -
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.
Lesson done
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.