Substrings and subsequences
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A substring is a connected piece of text, like the word cat inside concatenate. A subsequence picks characters in order but may skip some, like c-t from cat. Telling them apart matters because connected pieces use simple windows, while skipping pieces need smarter matching.
Practical use cases
- Web app: Fuzzy file jump in a code editor. A web-based editor lets you type ptjs and jump to project-tasks.js. The letters appear in the file name in order but not side by side, so the matcher checks for a subsequence. It is far more forgiving than needing an exact connected piece of the name.
- Web app: Find on page and highlighting. A help centre highlights every place where the typed phrase appears in an article. That phrase must appear as one connected piece, a substring. The code slides along the article looking for places where the typed text fits exactly. Because the match must be connected, a typo in the middle of the phrase finds nothing, as readers expect from a plain search.
- System: Diff tools and DNA comparison. A diff tool finds the longest set of lines two versions share in order, even with lines added between them, a subsequence. DNA comparison uses the same idea to line up two gene strings despite small insertions and mutations. Skipping is allowed but order is never broken, which is why the result can be shown to a human as a neat list of changes.
The story: The Cut Pieces of a Garland
At a temple, Zoya was handed a garland of flowers, one flower per letter: C, A, T. The priest said, "Give me a piece of the garland." Zoya cut it with scissors: a piece of two joined flowers, CA. "Perfect," said the priest, "a piece where the flowers still touch. That is a substring."
Then her little brother Aarav played a different game. He did not cut anything. He just pointed at the first flower and the last flower, ignoring the middle one: "C... T". "Clever," said Mira. "You skipped, but you kept the order. That is a subsequence." Aarav grinned. "Can I say T... C?" "No, the order must stay the way the garland hangs."
Kabir counted. A garland of 3 flowers has 6 pieces you can cut, but 8 ways to point (counting "point at nothing"). Add a few more flowers and the pointing ways explode far faster than the cutting ways. Knowing the difference saves you from solving the wrong problem later: substring means contiguous, subsequence means in order but may have gaps.
How to spot this problem, and where you need it
You are comparing or searching text and cannot tell whether matching characters must sit together or may be spread out, which changes both the answer and the method.
Signs you need it
- The problem says contiguous, consecutive or a piece of the text for a substring, or in order but not necessarily adjacent for a subsequence.
- A search should still succeed when the user types only some letters of a name, in order.
- A comparison feature should survive extra lines or characters inserted between matching parts.
Where to use it in a project
- Command palettes, file switchers and autocomplete boxes with fuzzy matching.
- Compare and merge features for documents, code and configuration, and find-in-page highlighting.
The solution
For substrings, slide a window along the text and compare it with the target at each position. For a subsequence check, keep one marker on the target and walk through the text once, advancing the target marker only when the current text character matches the next wanted character. If the target marker reaches the end, the target is a subsequence. For the longest shared subsequence, fill a table.
Payoff: Before: users must type the exact connected name to find a file. After: typing just a few letters in order finds it.
Explain it like I am 8
A substring is a bite out of a sandwich: the bite is one connected piece. A subsequence is picking toppings from the sandwich from left to right, skipping the ones you do not like, but never going back.
How it works, step by step
- Substring: pick a start position and an end position. Everything in between comes along, no gaps.
- Make all substrings with two loops: the outer loop picks the start, the inner loop stretches the end.
- Subsequence: for each letter, choose take or skip, and keep the original order.
- Make all subsequences with recursion: at each position, branch into "take it" and "skip it".
- Remember: every substring is also a subsequence, but a subsequence like "CT" is not a substring of "CAT".
The code in four languages
PHP
<?php
// All substrings: pick a start, then stretch the end one letter at a time.
function allSubstrings(string $s): array {
$out = [];
for ($start = 0; $start < strlen($s); $start++) {
for ($len = 1; $start + $len <= strlen($s); $len++) {
$out[] = substr($s, $start, $len);
}
}
return $out;
}
// All subsequences: at each letter, "take it" or "skip it".
function allSubsequences(string $s, int $i = 0, string $cur = ''): array {
if ($i === strlen($s)) {
return [$cur]; // decided about every letter
}
return array_merge(
allSubsequences($s, $i + 1, $cur . $s[$i]), // take
allSubsequences($s, $i + 1, $cur) // skip
);
}
echo json_encode(allSubstrings("CAT")) . "\n"; // ["C","CA","CAT","A","AT","T"]
echo json_encode(allSubsequences("CAT")) . "\n"; // 8 itemsJavaScript
// All substrings: pick a start, then stretch the end one letter at a time.
function allSubstrings(s) {
const out = [];
for (let start = 0; start < s.length; start++) {
for (let len = 1; start + len <= s.length; len++) {
out.push(s.substr(start, len));
}
}
return out;
}
// All subsequences: at each letter, "take it" or "skip it".
function allSubsequences(s, i = 0, cur = '') {
if (i === s.length) {
return [cur]; // decided about every letter
}
return allSubsequences(s, i + 1, cur + s[i]) // take
.concat(allSubsequences(s, i + 1, cur)); // skip
}
console.log(JSON.stringify(allSubstrings('CAT'))); // ["C","CA","CAT","A","AT","T"]
console.log(JSON.stringify(allSubsequences('CAT'))); // 8 itemsJava
import java.util.*;
public class Main {
// All substrings: pick a start, then stretch the end one letter at a time.
static List<String> allSubstrings(String s) {
List<String> out = new ArrayList<>();
for (int start = 0; start < s.length(); start++) {
for (int len = 1; start + len <= s.length(); len++) {
out.add(s.substring(start, start + len));
}
}
return out;
}
// All subsequences: at each letter, "take it" or "skip it".
static List<String> allSubsequences(String s, int i, String cur) {
if (i == s.length()) {
return List.of(cur); // decided about every letter
}
List<String> out = new ArrayList<>(allSubsequences(s, i + 1, cur + s.charAt(i))); // take
out.addAll(allSubsequences(s, i + 1, cur)); // skip
return out;
}
public static void main(String[] args) {
System.out.println(allSubstrings("CAT")); // [C, CA, CAT, A, AT, T]
System.out.println(allSubsequences("CAT", 0, "")); // [CAT, CA, CT, C, AT, A, T, ] (8 items, the last is empty)
}
}Go
package main
import "fmt"
// allSubstrings picks a start, then stretches the end one letter at a time.
func allSubstrings(s string) []string {
var out []string
for start := 0; start < len(s); start++ {
for length := 1; start+length <= len(s); length++ {
out = append(out, s[start:start+length])
}
}
return out
}
// allSubsequences decides at each letter: "take it" or "skip it".
func allSubsequences(s string, i int, cur string) []string {
if i == len(s) {
return []string{cur} // decided about every letter
}
taken := allSubsequences(s, i+1, cur+string(s[i])) // take
skipped := allSubsequences(s, i+1, cur) // skip
return append(taken, skipped...)
}
func main() {
fmt.Printf("%q\n", allSubstrings("CAT")) // ["C" "CA" "CAT" "A" "AT" "T"]
fmt.Printf("%q\n", allSubsequences("CAT", 0, "")) // ["CAT" "CA" "CT" "C" "AT" "A" "T" ""] (8 items)
}Time: Substrings O(n²) pieces · Subsequences O(2ⁿ) pieces · Extra space: O(n) depth for the recursion. A word of n letters has about n²/2 substrings but 2ⁿ subsequences, so listing all subsequences is only fine for short words.
Watch out for
- Mixing the two words up in an interview. "Substring" never has gaps. "Subsequence" may.
- Listing all subsequences of a long string. With 30 letters there are over a billion; use smarter methods (like dynamic programming) instead of listing them.
- Forgetting the empty subsequence when counting: 3 letters give 8, not 7.
Quick check
- Which is a subsequence of "CAT" but NOT a substring?
- CA
- CT
- AT
- How many substrings does a 3-letter word have?
- 6
- 8
- 3
- Is "TC" a subsequence of "CAT"?
- Yes
- Only if we skip A
- No, the order is wrong