oneby7

2-D Dynamic Programming Two strings

566. Print a Longest Common Subsequence

Medium

You are given two strings, s1 and s2. Return one of the longest strings that is a subsequence of both.

A subsequence of a string is what is left after deleting some of its letters, or none, without changing the order of the rest. "ace" is a subsequence of "abcde", but "eca" is not. The letters do not have to sit next to each other.

Often several longest common subsequences exist, and any of them is correct. If the strings share no letter, return the empty string "". Answers are shown in double quotes. When your string is a subsequence of both, the result shows its length, as a common subsequence of length 3. Otherwise it shows the first thing wrong with it, such as answer[1] = 'e' has no match in s1 after answer[0] = 'n' at index 5. Positions count from 0.

Example 1

Input: s1 = "listen", s2 = "silent"

Output: "len"

Explanation: In "listen" the letters of "len" sit at indexes 0, 4 and 5, and in "silent" at 2, 3 and 4. "ien" and "sen" are also correct. No common subsequence has 4 letters.

Example 2

Input: s1 = "moon", s2 = "sky"

Output: ""

Explanation: The strings share no letter, so the only common subsequence is the empty one.

Example 3

Input: s1 = "coffee", s2 = "office"

Output: "offe"

Explanation: Both fs and the first e of each string line up in order. The c cannot join them: it comes first in "coffee" but after both fs in "office".

Check your understanding

Work out the answer for this input before you write any code.

s1 = "garden", s2 = "danger"

Constraints

  • 1 ≤ s1.length, s2.length ≤ 3000
  • s1 and s2 hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.