InternDoor

Longest piece two strings share

Mediumstrings · dynamic programming

Reported in interviews at (where)

A substring is a run of characters next to each other: "view" is a substring of "review", but "rvw" is not.

Return the length of the longest string that is a substring of both a and b, or 0 if they share no character.

Example 1
Input
a = "interview"
b = "overview"
Output
6

"erview" appears in both, letter for letter in a row.

Example 2
Input
a = "banana"
b = "ananas"
Output
5

"anana" is at the end of the first and the start of the second.

Example 3
Input
a = "abc"
b = "def"
Output
0

No letter is shared.

Limits

  • 1 <= a.length, b.length <= 1000
  • a and b hold lowercase English letters

Hints

Hint 1

Let run(i, j) be the length of the longest common piece that ends exactly at a[i - 1] and b[j - 1].

Hint 2

If those two letters match, run(i, j) = run(i - 1, j - 1) + 1, otherwise it is 0. The answer is the largest run anywhere in the table.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.