Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
import longestCommonSubsequence from '../longestCommonSubsequenceRecursive';

describe('longestCommonSubsequenceRecursive', () => {
it('should distinguish memoized suffixes containing colons', () => {
expect(longestCommonSubsequence('::a:a', 'aa:::')).toBe(':::');
expect(longestCommonSubsequence('aa:::', '::a:a')).toBe(':::');
});

it('should reuse empty subsequences instead of expanding them repeatedly', () => {
const substring = jest.spyOn(String.prototype, 'substring');
let result;
let calls;
try {
result = longestCommonSubsequence('a'.repeat(8), 'b'.repeat(8));
calls = substring.mock.calls.length;
} finally {
substring.mockRestore();
}

expect(result).toBe('');
// There are 8 * 8 non-empty suffix pairs, with two branches per pair.
expect(calls).toBeLessThanOrEqual(2 * 8 * 8);
});

it('should find longest common substring between two strings', () => {
expect(longestCommonSubsequence('', '')).toBe('');
expect(longestCommonSubsequence('ABC', '')).toBe('');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*
* @param {string} string1
* @param {string} string2
* @return {number}
* @return {string}
*/
export default function longestCommonSubsequenceRecursive(string1, string2) {
/**
Expand All @@ -16,18 +16,22 @@ export default function longestCommonSubsequenceRecursive(string1, string2) {
const lcs = (s1, s2, memo = {}) => {
if (!s1 || !s2) return '';

if (memo[`${s1}:${s2}`]) return memo[`${s1}:${s2}`];
// Each call uses suffixes of the original inputs. Their lengths uniquely
// identify the pair, even when the input strings contain the separator.
const key = `${s1.length}:${s2.length}`;
if (memo[key] !== undefined) return memo[key];

if (s1[0] === s2[0]) {
return s1[0] + lcs(s1.substring(1), s2.substring(1), memo);
memo[key] = s1[0] + lcs(s1.substring(1), s2.substring(1), memo);
return memo[key];
}

const nextLcs1 = lcs(s1.substring(1), s2, memo);
const nextLcs2 = lcs(s1, s2.substring(1), memo);

const nextLongest = nextLcs1.length >= nextLcs2.length ? nextLcs1 : nextLcs2;

memo[`${s1}:${s2}`] = nextLongest;
memo[key] = nextLongest;

return nextLongest;
};
Expand Down