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

The shortest common supersequence

Medium · Target 20 minutes · Dynamic programming · Type asked atAmazon

Given strings a and b, return the length of the shortest string that has both a and b as subsequences.

Examples

InputOutputWhy
a = "abac", b = "cab"5"cabac".
a = "abc", b = "def"6Nothing can be shared.
a = "geek", b = "eke"5"geeke".

Constraints

  • 0 ≤ a.length, b.length ≤ 1000
  • Lowercase English letters

Hints

Hint 1

A supersequence writes every character of both strings, but a character common to both, in a shared order, needs writing only once.

Hint 2

The most that can be shared is the longest common subsequence.

Hint 3

Directly: scs[i][j] = 1 + scs[i − 1][j − 1] on a match, else 1 + min(scs[i − 1][j], scs[i][j − 1]).

Where people lose marks

  • Returning |a| + |b|, which ignores sharing.
  • Base cases of 0 instead of the remaining length of the other string.
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.