Print Longest Common Subsequence
Implement printLCS
Given two strings, reconstruct one actual longest common subsequence rather than just its length — the longest sequence of characters that appears in both strings in the same relative order, though not necessarily touching. When the two strings share nothing this way, the reconstructed answer is the empty string. Since more than one longest common subsequence can exist for the same pair of strings, ties are broken by preferring to skip a character of the first string over the second whenever both directions are equally good, so the result stays deterministic.
The same length-only table used to compute how long the common subsequence is also records enough information to rebuild it: a cell reached because both tail characters matched must have that character in the answer, and a cell reached because one string's tail character was dropped points toward whichever neighbor produced its value. Walking that table backward from the final cell — either through recursive calls that unwind in the correct order, or through an explicit loop whose output gets reversed at the end — replays exactly the choices that were made while filling it, turning the stored lengths back into one concrete subsequence.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: "ace"
Example 2:
Input: text1 = "abc", text2 = "def"
Output: ""
Example 3:
Input: text1 = "", text2 = "abc"
Output: ""
+ 7 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ text1.length, text2.length ≤ 12 - ●
text1 and text2 consist only of lowercase English letters - ●
If more than one longest common subsequence exists, return the one produced by preferring to move up (skip a character of text1) over moving left whenever both directions tie
text1 =
abcde
text2 =
ace