Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Longest common subsequence

Medium · Target 15 minutes · Dynamic programming · Type asked atAmazonGoogleMicrosoft

Given two strings text1 and text2, return the length of their longest common subsequence: a string that can be obtained from each of them by deleting some characters without reordering the rest. Return 0 if they share no character.

Examples

InputOutputWhy
text1 = "abcde", text2 = "ace"3"ace".
text1 = "abc", text2 = "def"0Nothing in common.
text1 = "ABCBDAB", text2 = "BDCABA"4For example "BCBA".

Constraints

  • 1 ≤ text1.length, text2.length ≤ 1000
  • Lowercase or uppercase English letters

Hints

Hint 1

Let L[i][j] be the answer for the prefixes text1[:i] and text2[:j]. Empty prefixes give 0.

Hint 2

If the last characters match, L[i][j] = 1 + L[i − 1][j − 1].

Hint 3

Otherwise one of the two last characters is not used: L[i][j] = max(L[i − 1][j], L[i][j − 1]).

Where people lose marks

  • Mixing prefix lengths and character indices: L[i][j] compares text1[i − 1] and text2[j − 1].
  • On a match, taking max(L[i − 1][j], L[i][j − 1]) + 1, which can count one character twice.
  • Confusing it with the longest common substring, which must be contiguous.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.