The longest common subsequence of {1,2,3,2,4,1,2} and {2,4,3,1,2,1} is

2025

The longest common subsequence of {1,2,3,2,4,1,2} and {2,4,3,1,2,1} is

  1. A.

    2,1,2,3

  2. B.

    1,3,2,1

  3. C.

    2,3,2,1

  4. D.

    2,3,1,2,1

Attempted by 341 students.

Show answer & explanation

Correct answer: C

Final answer: 2,3,2,1 (length 4)

Verification — show it is a subsequence of both sequences:

  • In the first sequence {1,2,3,2,4,1,2} take positions 2, 3, 4, 6 to get 2,3,2,1.

  • In the second sequence {2,4,3,1,2,1} take positions 1, 3, 5, 6 to get 2,3,2,1.

Why no longer common subsequence exists:

  • Any candidate longer than 4 would require additional occurrences of elements in one or both sequences that are not available in the required order. For example, a 5-element candidate like 2,3,1,2,1 cannot be matched in the first sequence because after matching 2 (pos 2), 3 (pos 3), 1 (pos 6) and 2 (pos 7) there is no remaining 1 after position 7.

  • A standard dynamic programming LCS computation produces maximum length 4 for these two sequences, so 2,3,2,1 is indeed a longest common subsequence.

Conclusion: 2,3,2,1 is a longest common subsequence of the given sequences.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Coding For Placement