Shared Dance Moves

Mediumdynamic programmingAlso known as Longest Common Subsequence

Two dance groups each have a routine written as one letter per move: S for a spin, J for a jump, P for a pose, and so on. For the joint finale they want to dance together, using moves that appear in both routines in the same order.

Each group may leave out moves but 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 both from first and from second by deleting some letters. Kept letters stay in their original order but need not be next to each other.

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

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

Examples

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

The moves P, J, T appear in order in both routines: at positions 1, 2 and 3 in SPJTS, and at positions 0, 2 and 4 in PSJST. S, J, S also works. No four moves appear in the same order in both, so the answer is 3.

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

Both have a spin and a jump, but in opposite orders. You can keep only one, 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 can also be made from the second. With 1,000 moves that is 2¹⁰⁰⁰ candidates.

Two tempting shortcuts are wrong. Counting common letters ignores order, so it says 2 for SJ and JS. Looking for a shared run of back-to-back moves 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