Longest Common Substring Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Longest Common Substring runs in O(n*m) time and O(n*m) space, in JavaScript as in every other language.
- ✓Nothing in the language or in Node implements this. String.prototype.indexOf, lastIndexOf, includes, startsWith and endsWith are the only substring primitives, and they are useful for the binary-search-on-length variant rather than the DP.
- ✓A reviewer rejects allocating a fresh new Array(m + 1).fill(0) per outer iteration - that is a boxed, potentially holey array - and insists on two reused Int32Arrays swapped by reference with .fill(0) between rows.
- ✓The JavaScript trap: Two traps that are specific to V8 string internals. First, a.slice(start, end) does not copy once the result reaches 13 characters (V8's SlicedString::kMinLength): V8 returns a SlicedString that keeps the entire parent alive, so pulling a 200-character match out of a 50 MB file retains all 50 MB until the match is collected.
- ✓Int32Array rows stay unboxed and are never scanned by the GC for pointers, which is most of the win over plain arrays.
What Longest Common Substring actually is
Longest Common Substring in JavaScript: what you actually reach for
JavaScript implementation
function longestCommonSubstring(a, b) {
const n = a.length;
const m = b.length;
let prev = new Int32Array(m + 1);
let cur = new Int32Array(m + 1);
let best = 0;
let endA = 0;
for (let i = 1; i <= n; i++) {
const ca = a.charCodeAt(i - 1);
cur.fill(0);
for (let j = 1; j <= m; j++) {
if (ca === b.charCodeAt(j - 1)) {
const run = prev[j - 1] + 1;
cur[j] = run;
if (run > best) {
best = run;
endA = i;
}
}
}
const swap = prev;
prev = cur;
cur = swap;
}
// Trim a dangling half of a surrogate pair off either end.
let s = endA - best;
let e = endA;
if (best > 0) {
const first = a.charCodeAt(s);
if (first >= 0xdc00 && first <= 0xdfff) s++;
}
if (e > s) {
const last = a.charCodeAt(e - 1);
if (last >= 0xd800 && last <= 0xdbff) e--;
}
// Array.from forces a real copy so the 50 MB parent can be collected.
return Array.from(a.slice(s, e)).join('');
}
console.log(longestCommonSubstring('abcdxyz', 'xyzabcd')); // abcd
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Longest Common Substring?
Nothing in the language or in Node implements this. String.prototype.indexOf, lastIndexOf, includes, startsWith and endsWith are the only substring primitives, and they are useful for the binary-search-on-length variant rather than the DP. The right stdlib pieces are the typed arrays: Int32Array or Uint32Array (globals, no import) for the two rolling rows, plus TypedArray.prototype.fill to reset a row. In the ecosystem, jsdiff (the diff package) and fast-diff implement Myers line/char diff, not longest common substring, so do not reach for them expecting this function.
What is the most common JavaScript mistake when implementing Longest Common Substring?
Two traps that are specific to V8 string internals. First, a.slice(start, end) does not copy once the result reaches 13 characters (V8's SlicedString::kMinLength): V8 returns a SlicedString that keeps the entire parent alive, so pulling a 200-character match out of a 50 MB file retains all 50 MB until the match is collected. Below 13 characters V8 copies into a fresh sequential string, so short matches are already safe. Force a real copy with Array.from(match).join('') when a longer match outlives the input. Second, JS strings are UTF-16 code units, so a byte-blind DP can start a match on a low surrogate; the resulting lone surrogate is silently replaced by U+FFFD when you hand it to TextEncoder or write it to a file.
How does Longest Common Substring actually perform in JavaScript?
Int32Array rows stay unboxed and are never scanned by the GC for pointers, which is most of the win over plain arrays. charCodeAt on a flat one-byte string is two loads, but if either input was built with += you have a cons string, and the first index into it triggers an O(n) flatten - inside your inner loop. Touch a.charCodeAt(0) once before timing anything. The loop is monomorphic only while both inputs keep the same internal representation; mixing a rope and a flat string deoptimises the compare site. Time complexity is O(n*m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.