Data Structures & AlgorithmsHardICPC regional · Product Company SDE

Problem: The longest common subsequence (LCS) of two strings of length n and m is typically solved with which approach and complexity?

  1. A. A single greedy pass, O(n+m)
  2. B. Bottom-up DP over an (n+1)x(m+1) table, O(nm) time and space
  3. C. Sorting both strings, O(n log n + m log m)
  4. D. Brute-force over all subsequences, O(2^n)

Correct answer: B. Bottom-up DP over an (n+1)x(m+1) table, O(nm) time and space

The classic LCS recurrence compares characters and takes the best of three sub-results, filled bottom-up in an (n+1)x(m+1) table: O(nm) time and space (space can be reduced to O(min(n,m)) with rolling rows).

More Coding Interview Problems questions

Exams that ask this topic