Compute longest common subsequence length
Company: Roku
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of dynamic programming and sequence processing, measuring competence in reasoning about optimal substructure, overlapping subproblems, and algorithmic complexity.
Constraints
- 0 <= len(s), len(t) <= 1000
- Strings contain ASCII letters (lowercase/uppercase)
Examples
Input: ("abcde", "ace")
Expected Output: 3
Explanation: The LCS is "ace" with length 3.
Input: ("abc", "def")
Expected Output: 0
Explanation: No characters are common, so the LCS length is 0.
Input: ("abc", "abc")
Expected Output: 3
Explanation: Identical strings share the whole string as a subsequence.
Input: ("", "abc")
Expected Output: 0
Explanation: An empty string shares no subsequence, so the length is 0.
Input: ("", "")
Expected Output: 0
Explanation: Two empty strings have an empty LCS of length 0.
Input: ("bl", "yby")
Expected Output: 1
Explanation: Only 'b' is common, giving LCS length 1.
Input: ("abcba", "abcbcba")
Expected Output: 5
Explanation: The LCS "abcba" has length 5.
Input: ("AGGTAB", "GXTXAYB")
Expected Output: 4
Explanation: The LCS is "GTAB" with length 4.
Hints
- Define dp[i][j] = length of the LCS of the first i characters of s and the first j characters of t.
- If s[i-1] == t[j-1], then dp[i][j] = dp[i-1][j-1] + 1; otherwise dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
- The base cases (empty prefix on either side) are all 0, so initialize the first row and column to 0.
- Space can be reduced to O(min(m, n)) by keeping only the previous and current rows.