We need to answer: "You are given a list of strings. Write a function to find the longest common subsequence. Please this is different from the longest common substring. A subsequence does not need to be contiguous, this is a classic dynamic programming problem, write a function that solves this problem, and explain your DP state and recurrence relation."
Interpretation: The input is a list of strings. But the classic longest common subsequence (LCS) problem is usually between two strings. However, the prompt says "a list of strings". That could mean we need to find the LCS among multiple strings? But typically LCS for multiple strings is NP-hard? Actually, longest common subsequence for more than two strings can be solved with dynamic programming, but the state space grows exponentially with the number of strings. However, there is a known algorithm for two strings. Possibly the problem expects to find LCS of two strings? But it says "a list of strings". Maybe it means given two strings? But it says "list", so maybe it's a list containing two strings? Or maybe it's a list of any number of strings, and we need to find the longest common subsequence among all of them? That is a generalization.
But the classic DP for two strings is standard. For multiple strings, the DP state is a multi-dimensional array, and the recurrence relation is similar but checking all strings. But the complexity becomes O(∏ n_i) which is not feasible for many strings. However, perhaps the problem expects the two-string version, and the "list of strings" might be a list with exactly two strings? But it says "a list of strings", not necessarily two.
Let's read carefully: "You are given a list of strings. Write a function to find the longest common subsequence." That is ambiguous. But then it says "this is different from the longest common substring. A subsequence does not need to be contiguous, this is a classic dynamic programming problem". That classic DP problem is indeed for two strings. But the phrasing "list of strings" might be a general case? Actually, the longest common subsequence problem for two strings is the classic one. For more than two, it's often called the multiple sequence alignment problem, and it's more complex.
Given that the user explicitly asks to explain DP state and recurrence relation, it's likely they want the two-string version. But they said "list of strings". Possibly they mean: the input is a list containing two strings? Or maybe they expect to handle any number of strings, but then we need to explain the DP for k strings? That would be a multi-dimensional DP. However, that is less common as a "classic dynamic programming problem". The classic is for two strings.
Maybe they want a function that takes a list of strings and returns the LCS of all strings in the list. If the list has only one string, then LCS is that string? If empty, empty? But the DP for multiple strings would be: Let S1, S2, ..., Sk be the strings. Define DP[i1][i2]...[ik] as the length of LCS of the prefixes S1[0:i1], S2[0:i2], ..., Sk[0:ik]. Then recurrence: if all characters at positions i1-1, i2-1, ..., ik-1 are equal, then DP[i1][i2]...[ik] = 1 + DP[i1-1][i2-1]...[ik-1]; else, DP[i1][i2]...[ik] = max( DP[i1-1][i2]...[ik], DP[i1][i2-1]...[ik], ..., DP[i1][i2]...[ik-1] )? Actually, for k strings, when not all equal, we need to consider decreasing any one of the indices. That gives k possibilities. So recurrence: DP[i1,...,ik] = max over all j from 1 to k of DP with the j-th index decreased by 1. That is correct. But then we need to compute the max of k terms. That's a generalization.
But is that considered "classic"? Possibly, but the two-string case is the most classic.
Given the context of an interview or typical question, they might mean two strings. But they said "list of strings". Could be a misstatement.
Maybe the function should take two strings as arguments? But then it says "list", so maybe the function signature is something like: def longest_common_subsequence(strings): where strings is a list. And if the list has more than two, we need to find the LCS among all? That is a known problem, but it's not trivial to implement efficiently for arbitrary number of strings.
Alternatively, maybe they want to find the longest common subsequence among all strings in the list, which is equivalent to finding the LCS of all of them. For two strings it's straightforward. For more, we can do pairwise and then combine? But that might not give the correct result for multiple strings.
Given the emphasis on DP state and recurrence relation, I think it's safe to assume they want the two-string version. But to be safe, I could mention both: first solve for two strings, and then note that for multiple strings, we can extend the DP to multiple dimensions, but that's computationally expensive.
But the user says: "Write a function to find the longest common subsequence." So I should write code. I'll write a function that takes a list of strings. If the list is empty, return "". If it has one string, return that string? But that's trivial. If it has two or more, we can compute LCS iteratively: start with first string, then compute LCS with second, then use that result as the new reference and compute with third, etc. But that does not necessarily give the LCS of all strings? Actually, the LCS of a set of strings is a string that is a subsequence of every string. If we compute LCS(A,B) = X, then LCS(X,C) might not be the LCS of A,B,C because there might be a common subsequence of A,B,C that is longer than any common subsequence of X and C. Example: A="abc", B="acb", C="bac". LCS(A,B) could be "ab" or "ac". Suppose we pick "ab". Then LCS("ab", C) is "a" or "b" (since "ab" is not a subsequence of "bac"? Actually "ab" is not a subsequence of "bac", because in "bac", 'a' comes before 'b'? Wait "bac": positions: b(0), a(1), c(2). To get "ab", we need 'a' before 'b', but in "bac" 'a' is at index1 and 'b' at index0, so we cannot have 'a' then 'b'? Actually we need increasing indices, so we need to pick 'a' at index1 and then 'b' at index0? That's not increasing. So "ab" is not a subsequence of "bac". So LCS("ab","bac") would be length 1. But the true LCS of A,B,C might be "a" or "b" or "c". But consider another example: A="abc", B="acb", C="ab". LCS(A,B) could be "ab". Then LCS("ab", C) is "ab". That's correct. But it's not always correct. Actually, the LCS of multiple strings is not necessarily obtained by iteratively pairwise LCS. Because the pairwise LCS might choose a subsequence that does not appear in the third string. So to get the true LCS of all strings, we need a multi-string DP.
But the problem statement: "You are given a list of strings." That implies possibly more than two. But then it says "this is a classic dynamic programming problem", which for multiple strings is also DP but with high dimensionality. Possibly they expect the two-string version, and the list is just containing two strings.
Given the ambiguity, I'll implement a function that handles any number of strings, using DP for multiple strings. But for more than two, the DP table size can be huge. However, for the sake of completeness, I'll write a general DP that works for any number but will be exponential in the number of strings. That might be acceptable as an explanation, but for practical use, we would only use for small k and small lengths.
Alternatively, I can implement the two-string version and then mention how to extend.
Let's see the request: "explain your DP state and recurrence relation." So I need to explain that. I'll explain for two strings first, and then mention the generalization.
But the user might expect the function to take a list and return the LCS of all strings. I'll write a function that does exactly that. For two strings, it's the classic DP. For more, I'll use a multidimensional DP? But implementing that for arbitrary number of strings in Python with recursion or loops might be messy because the number of dimensions is variable. We can use recursion with memoization over a tuple of indices. That is a standard way: define a function lcs(indices) where indices is a tuple of current positions in each string. Then if all strings at those positions have the same character, we add 1 and recurse with all indices decremented. Otherwise, we take the max of recursing with each index decremented by one. That is a recursive DP with memoization. That works for any number of strings, but the state space is product of lengths, which is exponential in the number of strings if lengths are fixed? Actually, it's O(∏ n_i). So for k strings, it's the product. So if we have many strings or long strings, it's not feasible. But for the purpose of this problem, we assume small input.
So I'll implement a recursive DP with memoization for a list of strings. That is general and matches the "list of strings" description.
But then the DP state is: for a given tuple of positions (i1, i2, ..., ik), where ij is the current index in string j (starting from the end, or from the beginning). Typically we define from the beginning: DP[i1][i2]...[ik] = LCS length of suffixes starting at i1, i2, ... or prefixes? Usually we define for prefixes: DP[i][j] for two strings is LCS of s1[0:i] and s2[0:j]. For multiple, similarly: DP[i1][i2]...[ik] = LCS of s1[0:i1], s2[0:i2], ..., sk[0:ik]. That's fine.
But in the recursive approach, we can work from the end: function f(i1, i2, ..., ik) returns LCS of s1[i1:], s2[i2:], ... (suffixes). Then recurrence: if i1==len(s1) or any is at end, return 0. If all characters at current positions are equal, then return 1 + f(i1+1, ..., ik+1). Else, return max( f(i1+1, i2, ..., ik), f(i1, i2+1, ..., ik), ..., f(i1, i2, ..., ik+1) ). That's the recurrence.
We can implement that recursively with memoization. That is easy for any number of strings because we can pass a tuple of indices.
So I'll write a function:
def longest_common_subsequence(strings):
if not strings:
return ""
# if only one string, return it
if len(strings) == 1:
return strings[0]
# use memoization
memo = {}
n = [len(s) for s in strings]
def dp(indices):
# indices is a tuple of current positions
if any(indices[i] >= n[i] for i in range(len(indices))):
return ""
# check memo
if indices in memo:
return memo[indices]
# if all characters at current indices are equal
chars = [strings[i][indices[i]] for i in range(len(indices))]
if all(c == chars[0] for c in chars):
# include this character
res = chars[0] + dp(tuple(indices[i]+1 for i in range(len(indices))))
else:
# try skipping one character from each string
options = []
for i in range(len(indices)):
new_indices = list(indices)
new_indices[i] += 1
options.append(dp(tuple(new_indices)))
# choose the longest
res = max(options, key=len)
memo[indices] = res
return res
result = dp(tuple([0]*len(strings)))
return result
But this returns the actual subsequence string. That's what we want: "find the longest common subsequence". So we need to return the string.
But note: This recursive DP returns the string directly. However, the typical DP for two strings builds a table of lengths and then backtracks to get the string. But with recursion and memoization returning strings, we are storing strings in memo, which might be memory heavy but okay for small inputs. Alternatively, we can store lengths and then backtrack, but that's more complex for multiple dimensions.
Given that we want to explain DP state and recurrence, I can explain the recursive version with memoization. But the user might expect the iterative DP table for two strings. Since they said "classic dynamic programming problem", they might be expecting the 2D table.
Given the prompt, I'll provide a solution that works for a list of strings, and in the explanation, I'll describe the DP state as a tuple of indices, and recurrence as above. But I'll also mention the two-string case as a special case with a 2D table.
To be thorough, I'll write a function that handles two strings efficiently with a 2D table, and for more than two, use the recursive multi-dimensional approach? But the problem says "a list of strings", so I should handle any length. However, if I implement the recursive version for any number, that's fine.
But I must consider performance: for two strings, the recursive version with memoization is still O(nm) states, so it's okay. But for three strings, it's O(n1n2*n3). So if the strings are long, it's bad. But for the purpose of this problem, we assume reasonable lengths.
Maybe the intended solution is the two-string DP. I'll check the wording: "You are given a list of strings." That might be because they want to pass two strings as a list? For example, in Python, you might pass a list of two strings. But then why say "list" instead of "two strings"? Possibly they want to generalize later.
Another thought: sometimes people say "list of strings" meaning an array of strings, but the problem is to find the LCS of all of them. I think it's safer to implement for multiple strings.
I'll implement a function that takes a list of strings and returns the LCS. I'll use memoization with a dictionary keyed by tuple of indices. And I'll explain the DP state and recurrence.
But in the recurrence, when not all characters match, we need to take the maximum over all possibilities of advancing one index. That is correct.
However, there is a nuance: when we take the max over options, we are comparing strings. That works because we want the longest string. If multiple have same length, any is fine.
But careful: when we do res = max(options, key=len), that will pick the longest string among the options. But note that the options are the results of recursive calls. That is correct.
But we also need to consider that when we skip a character, we are not adding anything. So the recurrence is:
If all current characters are equal, then LCS = that character + LCS of the next positions.
Otherwise, LCS = max_{i} LCS of the state with index i advanced (i.e., skip the current character of string i).
That is the recurrence.
Now, the DP state: for a given tuple of positions (i1, i2, ..., ik), it represents the longest common subsequence of the suffixes s1[i1:], s2[i2:], ..., sk[ik:].
We memoize on that tuple.
Base case: if any index is at the end of its string, the LCS is empty string.
That's it.
But for efficiency, we might want to return the length and then reconstruct, but here we return the string directly.
But storing strings in memo might be heavy. For two strings, we often store lengths and then backtrack. But for multiple strings, backtracking is more complicated. However, for simplicity, I'll do this.
Alternatively, we can store only lengths and then reconstruct by following the same decisions. But that would require storing additional information (which choice was made). That is possible but more complex.
Given that the problem likely expects an explanation of the DP state and recurrence, and the code, I'll provide the memoized recursion.
But wait: the classic DP for two strings uses a table dp[i][j] for lengths. Then we fill the table iteratively. That is also fine. I can implement that for two strings, and for more than two, I can either reduce to pairwise? But that's not correct as argued. So I need a general solution.
Maybe the problem expects only two strings. Given the prevalence of that problem, I think it's more likely. But the user explicitly says "list of strings", which might be to allow any number.
I'll answer with a general solution and explain for the general case. But in the explanation, I'll describe the state as a tuple of positions.
I'll write code accordingly.
Potential pitfalls: When all strings are empty, return "". When one string is empty, return "".
Also, when all current characters match, we include that character and move all indices forward. But what if there are repeated characters? That's fine.
Now, about the recursion depth: if the total length is large, recursion might hit limit. But for demonstration, it's okay.
We can also implement iteratively using a multi-dimensional array, but that's not possible for variable number of strings.
So I'll go with recursive memoization.
Let's write the function:
def longest_common_subsequence(strings):
if not strings:
return ""
if len(strings) == 1:
return strings[0]
# Convert to list of strings? Already list.
n = [len(s) for s in strings]
memo = {}
def dp(indices):
# indices: tuple of int
if any(indices[i] >= n[i] for i in range(len(indices))):
return ""
if indices in memo:
return memo[indices]
# Check if all current characters are the same
current_chars = [strings[i][indices[i]] for i in range(len(indices))]
if all(c == current_chars[0] for c in current_chars):
# All match
next_indices = tuple(indices[i] + 1 for i in range(len(indices)))
res = current_chars[0] + dp(next_indices)
else:
# Try skipping each string's current character
candidates = []
for i in range(len(indices)):
new_indices = list(indices)
new_indices[i] += 1
candidates.append(dp(tuple(new_indices)))
# Choose the longest candidate
res = max(candidates, key=len)
memo[indices] = res
return res
start = tuple(0 for _ in strings)
return dp(start)
But there is a subtlety: when we skip a character, we are not necessarily advancing only one index. In the recurrence for multiple strings, when not all characters match, we should consider all possibilities of decreasing any one of the indices? Actually, in the suffix version, we consider advancing (incrementing) the index of any one string. That is correct because we want to consider the LCS of suffixes where we ignore the current character of one string. But is it sufficient to only advance one at a time? For two strings, the recurrence is: if s1[i]==s2[j], dp[i][j] = 1+dp[i+1][j+1]; else dp[i][j] = max(dp[i+1][j], dp[i][j+1]). That's advancing one index. For k strings, the analogous is: if all k characters equal, then 1 + dp[i1+1,...,ik+1]; else, dp[i1,...,ik] = max over all j of dp with ij advanced by 1. That is correct because we are considering which string to skip a character from. But is it enough to only skip one at a time? Could we need to skip multiple at once? The recurrence with max over single increments covers all possibilities because we can increment one index multiple times through recursive calls. So it's fine.
But note: in the else branch, we are taking the max over the results of dp with each index advanced by one. That is correct.
But what about the possibility that we might want to skip more than one character from the same string before matching? That will be covered by recursive calls that repeatedly skip that string.
So the recurrence is correct.
Now, the DP state: we are using indices starting from 0 to length. That's fine.
But we must be careful: when all strings have the same character at current indices, we include it and advance all. That is the only way to include a character in the LCS.
Now, the time complexity: number of states is product of lengths. For two strings, it's O(n*m). For k strings, O(∏ n_i). That's exponential in k, but polynomial if k is fixed.
Now, the explanation: I'll describe the DP state and recurrence as above.
But the user might expect the iterative 2D DP. Since the problem says "classic dynamic programming problem", I think it's the two-string version. But to be safe, I'll provide both: I'll first implement the two-string version with a 2D table, and then mention that for more than two strings, we can generalize using a multi-dimensional DP or recursion with memoization.
But the function signature is to take a list of strings. So I need to handle any number. I'll write the function to check the length: if the list has exactly two strings, I can use an efficient 2D DP. Otherwise, use the recursive general approach. That would be efficient for two strings and still correct for more.
But the two-string iterative DP returns the length and then we can reconstruct the string. That is standard.
Let me implement that:
def longest_common_subsequence(strings):
if not strings:
return ""
if len(strings) == 1:
return strings[0]
if len(strings) == 2:
s1, s2 = strings
m, n = len(s1), len(s2)
# dp[i][j] = length of LCS of s1[:i] and s2[:j]
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# backtrack to get the LCS string
i, j = m, n
lcs_chars = []
while i > 0 and j > 0:
if s1[i-1] == s2[j-1]:
lcs_chars.append(s1[i-1])
i -= 1
j -= 1
elif dp[i-1][j] > dp[i][j-1]:
i -= 1
else:
j -= 1
return ''.join(reversed(lcs_chars))
else:
# General case for multiple strings using recursion with memoization
n = [len(s) for s in strings]
memo = {}
def dp(indices):
if any(indices[i] >= n[i] for i in range(len(indices))):
return ""
if indices in memo:
return memo[indices]
chars = [strings[i][indices[i]] for i in range(len(indices))]
if all(c == chars[0] for c in chars):
next_indices = tuple(indices[i]+1 for i in range(len(indices)))
res = chars[0] + dp(next_indices)
else:
options = []
for i in range(len(indices)):
new_indices = list(indices)
new_indices[i] += 1
options.append(dp(tuple(new_indices)))
res = max(options, key=len)
memo[indices] = res
return res
return dp(tuple([0]*len(strings)))
That should work.
But note: in the general case, when we have many strings, the recursion might be very deep. But for small cases it's fine.
Now, for the explanation:
For two strings:
DP state: dp[i][j] represents the length of the longest common subsequence of the prefixes s1[0:i] and s2[0:j] (i and j are lengths, so up to i and j characters).
Recurrence:
If s1[i-1] == s2[j-1], then dp[i][j] = 1 + dp[i-1][j-1].
Else, dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
Base: dp[0][j] = dp[i][0] = 0.
We fill the table and then backtrack to get the LCS string.
For multiple strings:
DP state: For a tuple of indices (i1, i2, ..., ik), let dp(i1, i2, ..., ik) be the longest common subsequence of the suffixes s1[i1:], s2[i2:], ..., sk[ik:].
Recurrence:
If any ij equals the length of string j, then dp = "" (empty).
If all characters s1[i1], s2[i2], ..., sk[ik] are equal, then dp = that character + dp(i1+1, i2+1, ..., ik+1).
Otherwise, dp = max_{j} dp(i1, ..., ij+1, ...), i.e., the best among skipping the current character of each string.
We use memoization to avoid recomputation.
That's the explanation.
Now, I'll produce the final answer with code and explanation.
But the user said "write a function that solves this problem, and explain your DP state and recurrence relation." So I need to present both.
I'll write the code as a function that takes a list of strings. I'll use the combined approach above.
But wait: the iterative 2D DP for two strings is more efficient and doesn't use recursion depth. So I'll keep that for two strings. For more, the recursive memoization might be slower but works.
Now, about the backtracking: In the two-string case, we build the table of lengths and then backtrack from (m,n). That's standard.
In the general recursive case, we are building the string directly via recursion. That's fine.
But there is a potential issue: when we take max(options, key=len), if there are multiple options with the same length, we pick one arbitrarily. That's acceptable.
Now, test with simple examples:
strings = ["ABCD", "ACBAD"] -> LCS = "ABD" or "ACD"? Actually, common subsequences: "ABD" (A from index0, B from index1, D from index3? Wait: "ABCD": A(0), B(1), C(2), D(3); "ACBAD": A(0), C(1), B(2), A(3), D(4). We can have "ABD": A from index0, B from index1? But in second string, B is at index2, so we need A at index0, then B at index2, then D at index4. That works. Also "ACD": A(0), C(2), D(3) in first; A(0), C(1), D(4) in second. So both length 3. So LCS length 3. Our algorithm might return one of them.
For two strings, the DP table method will produce one depending on the backtracking rule: when equal, we go diagonal; when not, we go up or left based on which is larger. If equal, we typically go up (or left? Actually, if dp[i-1][j] >= dp[i][j-1], we go up? In my code, I go up if dp[i-1][j] > dp[i][j-1], else go left. If equal, I go left. That might produce a different LCS but same length.
So it's fine.
For three strings: strings = ["abc", "acb", "bac"] -> common subsequences: single characters: 'a','b','c' are all present? 'a' is in all? "abc": has a; "acb": has a; "bac": has a. So 'a' is common. Similarly 'b' and 'c'. So LCS length 1. Our algorithm should return one of them.
Let's test mentally: start indices (0,0,0). chars: 'a','a','b' -> not all equal. So we skip each:
skip first: indices (1,0,0) -> chars: 'b','a','b'? Not all equal. Then etc.
skip second: (0,1,0): 'a','c','b' -> not all.
skip third: (0,0,1): 'a','a','a'? strings[0][0]='a', strings[1][0]='a', strings[2][1]='a'? Actually strings[2]="bac", index1 is 'a'. So all 'a'. So that gives 'a' + dp(1,1,2). At (1,1,2): indices beyond? strings[2] length is 3, index2 is 2, char='c'? Actually "bac": index0='b',1='a',2='c'. So at (1,1,2): s1[1]='b', s2[1]='c', s3[2]='c' -> not all equal. Then we try skipping each... eventually will get empty. So result "a". That works.
So the algorithm seems correct.
Now, about performance: For two strings, we use O(m*n) time and space. For more, it's exponential.
Given that, I'll present the solution.
Now, for the explanation part, I need to clearly state the DP state and recurrence.
I'll write:
For two strings:
DP state: dp[i][j] = length of LCS of s1[0:i] and s2[0:j].
Recurrence:
if s1[i-1] == s2[j-1]: dp[i][j] = 1 + dp[i-1][j-1]
else: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
Base: dp[0][j] = dp[i][0] = 0.
Then we backtrack to construct the LCS.
For multiple strings:
DP state: dp(i1, i2, ..., ik) = longest common subsequence of the suffixes starting at positions i1, i2, ..., ik in each string.
Recurrence:
If any ij == len(strings[j]), return "".
If all strings[j][ij] are equal, then return that character + dp(i1+1, ..., ik+1).
Otherwise, return max over j of dp(i1, ..., ij+1, ...) (i.e., skip the current character in the j-th string).
We memoize the results to avoid recomputation.
That's it.
Now, I'll provide the code.
But I'll also note that for two strings, the iterative DP is more efficient.
I think that's comprehensive.
Now, produce final answer.
Solution Explanation
The problem asks for the longest common subsequence (LCS) among a list of strings. A subsequence does not need to be contiguous, only that the characters appear in the same relative order. For two strings, the classic dynamic programming solution uses a 2‑dimensional table. For more than two strings we can generalise the DP to a multi‑dimensional state, but the state space grows exponentially with the number of strings. The solution below handles any number of strings: for exactly two strings it uses the efficient iterative DP; for three or more it uses a recursive memoised DP (which is still correct but may be slow for large inputs).
DP State and Recurrence
Two Strings (s1, s2)
Let dp[i][j] be the length of the LCS of the prefixes s1[:i] and s2[:j] (i.e. considering the first i characters of s1 and first j of s2).
Recurrence:
After filling the table, we backtrack from dp[m][n] to reconstruct the actual LCS string.
General Case (≥2 strings)
Let the strings be S[0], S[1], ..., S[k-1].
Define a state by a tuple of indices (i0, i1, ..., ik-1) where ij points into S[j].
dp(i0, i1, ..., ik-1) returns the longest common subsequence of the suffixes S[0][i0:], S[1][i1:], ..., S[k-1][ik-1:].
Recurrence:
- If any
ij reaches the end of its string (ij == len(S[j])), the LCS is empty: return "".
- If all current characters are equal (
S[0][i0] == S[1][i1] == ... == S[k-1][ik-1]), we include that character and advance all indices:
return S[0][i0] + dp(i0+1, i1+1, ..., ik-1+1)
- Otherwise we try skipping the current character of each string one at a time and take the best result:
options = [ dp(i0, ..., ij+1, ...) for each j ]
return the longest string among options
We memoise results for each tuple of indices to avoid redundant work.
Complexity Analysis
Two strings:
Time: O(m * n) where m = len(s1), n = len(s2) (filling the table).
Space: O(m * n) for the table (can be reduced to O(min(m,n)) if only lengths are needed, but we also backtrack).
General case (k strings):
Number of states = product of lengths: O(∏_{j=0}^{k-1} len(S[j])).
Each state does O(k) work (checking characters and exploring up to k branches).
Thus time and space are exponential in k but polynomial if k is treated as constant. This is acceptable for small numbers of strings (as typical in interview problems).
Reference Implementation (Python)
def longest_common_subsequence(strings):
"""
Find the longest common subsequence among a list of strings.
For exactly two strings an efficient iterative DP is used.
For three or more strings a recursive memoised DP is used.
"""
if not strings:
return ""
if len(strings) == 1:
return strings[0]
# Special case: exactly two strings -> iterative DP with backtracking
if len(strings) == 2:
s1, s2 = strings
m, n = len(s1), len(s2)
# dp[i][j] = length of LCS of s1[:i] and s2[:j]
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
# Backtrack to construct LCS string
i, j = m, n
lcs_rev = []
while i > 0 and j > 0:
if s1[i - 1] == s2[j - 1]:
lcs_rev.append(s1[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return ''.join(reversed(lcs_rev))
# General case: >=3 strings, recursive DP with memoisation
lengths = [len(s) for s in strings]
memo = {}
def dp(indices):
"""Return LCS of suffixes starting at given indices (tuple)."""
# Base: any index out of range -> empty string
if any(indices[i] >= lengths[i] for i in range(len(indices))):
return ""
if indices in memo:
return memo[indices]
# Characters at current positions
chars = [strings[i][indices[i]] for i in range(len(indices))]
if all(c == chars[0] for c in chars):
# All equal: include and advance all
next_indices = tuple(indices[i] + 1 for i in range(len(indices)))
result = chars[0] + dp(next_indices)
else:
# Try advancing each index separately, take longest
candidates = []
for i in range(len(indices)):
new_indices = list(indices)
new_indices[i] += 1
candidates.append(dp(tuple(new_indices)))
result = max(candidates, key=len)
memo[indices] = result
return result
return dp(tuple([0] * len(strings)))
How it works:
- For two strings we build a classic DP table of lengths and then backtrack to retrieve the subsequence.
- For more strings we recursively explore the state space defined by the current positions in each string, memoising to avoid recomputation. The recurrence directly builds the LCS string by either taking a matching character or skipping one.
This implementation correctly returns one of the longest common subsequences (any one is acceptable when there are ties).