Skip to content

longestCommonSubsequenceRecursive: wrong result when strings contain ':' and exponential time when there is no common character #2233

Open

Description

@devladpopov

Two bugs in src/algorithms/sets/longest-common-subsequence/longestCommonSubsequenceRecursive.js.

1. Wrong result. The memo key is `${s1}:${s2}` (lines 19 and 30), which is ambiguous when the strings contain :. For example, (':a:a', '::') and (':a', 'a:::') both map to ":a:a:::".

longestCommonSubsequenceRecursive('::a:a', 'aa:::');  // 'aa'   expected length 3 (':::')

This is the minimal case found by exhaustive search.

2. Exponential time. if (memo[key]) treats a memoised '' as a cache miss, so any pair of strings with no common characters is never memoised.

n ('a'.repeat(n) vs 'b'.repeat(n)) 8 12 13 14
time 8 ms 1.2 s 4.5 s 22 s

Fix: key on the suffix lengths (${s1.length},${s2.length}) and check key in memo. With both fixes, n = 13 takes 2.6 ms and n = 200 takes 20 ms.


Found during an independent property-based audit of this repo (full report and reproducible harness: https://github.com/devladpopov/algorithm-autopsy/tree/main/autopsy-02).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions