Shared Dance Moves

Mediumdynamic programmingAlso known as Longest Common Subsequence

Two dance groups are performing a joint finale. Each group has its own routine, written down as one letter per move: S for a spin, J for a jump, P for a pose, and so on. For the last minute, both groups want to dance together, so the finale uses moves that appear in both routines, in the same order.

Each group may leave out moves from its own routine, but it may not reorder them. How long can the shared finale be?

Your task

Write sharedMoves(first, second). Return the length of the longest sequence of letters that can be made from first by deleting some letters, and also from second by deleting some letters. The kept letters stay in their original order but do not need to be next to each other.

If either routine is empty, or they share no move at all, return 0.

sharedMoves(first: string, second: string) → int

Examples

Example 1
Input
first = "SPJTS"
second = "PSJST"
Output
3
Why

P, J, T appears in order in both: in SPJTS at positions 1, 2, 3, and in PSJST at positions 0, 2, 4. S, J, S also works. No 4 moves appear in the same order in both.

Example 2
Input
first = "SJ"
second = "JS"
Output
1
Why

Both routines have a spin and a jump, but in opposite orders. You can keep only one of them, so the answer is 1, not 2.

Constraints

  • 0 ≤ first.length, second.length ≤ 1,000
  • Both strings contain only uppercase letters A to Z.
Start with brute force

List every way to delete letters from the first routine (2ⁿ choices), and check whether each result can also be made from the second. With 1,000 moves that is 2¹⁰⁰⁰ candidates.

Counting the letters the two routines have in common is fast but ignores order: it says 2 for SJ and JS. Looking only for a shared run of back-to-back moves is also wrong: it misses moves that are spread out.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code