A plagiarism checker compares two essays and highlights the longest passage they share word for word. Unlike a common subsequence, the shared part must be contiguous in both texts.
Write two functions that take two strings a and b:
longestCommonSubstring(a, b) returns { text, startA, startB }: the longest string that appears as a contiguous substring of both, and the index where that occurrence starts in a and in b. Return null when the strings share no character (including when either is empty).
commonSubstringLength(a, b) returns just the length, or 0.
Rules:
Characters are compared exactly as JavaScript string units (a[i] === b[j]): case matters and no normalisation happens.
If several common substrings share the longest length, pick the one with the smallest startA, and for that one the smallest startB.
Throw a TypeError if a or b is not a string.
Strings can be 3,000 characters long. Testing every substring of a with b.includes takes far too long; aim for O(|a| × |b|) time and O(|b|) extra space.
longestCommonSubstring("ABABC", "BABCA"); // { text: "BABC", startA: 1, startB: 0 }longestCommonSubstring("abcxyz", "xyzabc"); // { text: "abc", startA: 0, startB: 3 }: ties go to the smaller startAlongestCommonSubstring("cat", "dog"); // nullcommonSubstringLength("banana", "ananas"); // 5 ("anana")
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.