Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Longest Common Substring Implementation in JavaScript

14 min readintermediate
Website QA and SEO audits

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

The longest run of CONSECUTIVE elements that appears in both sequences - not to be confused with longest common subsequence, which may skip elements. The textbook solution is a table where dp[i][j] holds the length of the match ending exactly at a[i-1] and b[j-1]: equal elements extend the diagonal, unequal elements reset to zero, and you track the running maximum. Engineers reach for it in diff tools looking for anchor blocks, plagiarism and duplicate-content checks, read overlap in bioinformatics, log deduplication, and fuzzy matching of product titles. Suffix automata or suffix arrays get you to O(n+m) when the inputs are large enough to care.

Longest Common Substring in JavaScript: what you actually reach for

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.

JavaScript implementation

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. They reject s.split('') to get characters, reject for...in over an array, and expect charCodeAt in the hot loop rather than bracket indexing, which materialises a one-character string. === always, and the returned value should be a slice, not a += accumulation.
javascript
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 Free

The JavaScript-specific 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. 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.

Performance in JavaScript, beyond the O(n*m)

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. The asymptotic cost is the same in every language, O(n*m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Longest Common Substring between languages.

Real-World Applications

Longest Common Substring applies wherever its problem shape appears in your own code. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Longest Common Substring helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Longest Common Substring appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Longest Common Substring over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Longest Common Substring to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.