Find longest common subsequence length
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of dynamic programming and sequence comparison algorithms by asking for the length of the longest common subsequence between two strings.
Constraints
- 0 <= len(s), len(t) <= 2000
- Strings may be empty
- Characters are ASCII letters or general bytes
- An O(len(s) * len(t)) dynamic programming solution is acceptable
Examples
Input: ("abcde", "ace")
Expected Output: 3
Explanation: "ace" is a common subsequence of both strings, and no longer common subsequence exists.
Input: ("abc", "abc")
Expected Output: 3
Explanation: The entire string matches, so the LCS length is 3.
Input: ("abc", "def")
Expected Output: 0
Explanation: The two strings share no common characters, so the longest common subsequence has length 0.
Input: ('', 'abc')
Expected Output: 0
Explanation: If one string is empty, there cannot be any common subsequence other than the empty one.
Input: ("aggtab", "gxtxayb")
Expected Output: 4
Explanation: One longest common subsequence is "gtab", which has length 4.
Input: ("aaaa", "aa")
Expected Output: 2
Explanation: Repeated characters still count in order; the longest common subsequence is "aa".
Hints
- Think about prefixes: what is the answer for s[:i] and t[:j] based on smaller prefixes?
- If the current characters match, you can extend a smaller subsequence; otherwise, you may need to skip one character from either string.