VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-longest-common-sub-sequences-lexicographical-order/

⇱ All LCS in Lexicographical Order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All LCS in Lexicographical Order

Last Updated : 14 Jun, 2026

Given two strings s1 and s2, return all distinct Longest Common Subsequences (LCS) in lexicographical order.

Examples: 

Input: s1 = "abac", s2 = "aabca"
Output: ["aac", "aba", "abc"]
Explanation: Every subsequence that appears in both "abac" and "aabca" with the maximum possible length 3, are ["aac" ,"aba", "abc"]

Input: s1 = "baaa", s2 = "ca"
Output: ["a"]
Explanation: Every subsequence common to "baaa and "ca" of maximum length 1, is ["a"].

[Naive Approach] Generate All Subsequences - O(2ⁿ × (m + n)) Time and O(2ⁿ) Space

Generate all subsequences of s1 using bitmask. Check each subsequence if it exists in s2 using two-pointer subsequence check. Track the maximum length and collect all distinct subsequences of that length.


Output
["aac", "aba", "abc"]

[Expected Approach] DP with Backtracking - O(m × n + L × 26 × (m + n)) Time and O(m × n) Space

Compute LCS length using DP table. Then backtrack to construct all distinct LCS strings by trying characters from 'a' to 'z' at each step, ensuring lexicographic order and only following paths that lead to full LCS length.

  • Build DP table where dp[i][j] stores LCS length for s1[i..] and s2[j..]. The length of LCS is stored at dp[0][0]. Get lcsLen = dp[0][0]
  • Backtrack from (0,0) with empty current string. If current length becomes lcsLen, add to result
  • Try characters 'a' to 'z' in order. For each char, find next occurrence in s1 and s2 where dp[ii][jj] equals remaining length
  • Recurse with ii+1, jj+1 after adding char

Illustration:



Output
["aac", "aba", "abc"]
Comment
Article Tags: