ITPEC FE Subject B October 2024 Question 7
From the answer group below, select the correct combination of answers to be inserted into A and B in the program.
Given two strings, str1 and str2, the task is to determine the length of the longest common subsequence (LCS), that is, the length of the longest subsequence present in both strings. For instance, if str1 is “ABXDZ” and str2 is “ABCD”, the LCS between str1 and str2 will be “ABD” and the length of the LCS will be 3.
The function lcs( takes two strings str1 and str2 and two integers m and n as arguments. str1 and str2 are the strings on which the length of the LCS is calculated. m and n are indexes addressing the target characters in str1 and str2, respectively. On the first call, m and n represent the lengths of str1 and str2, respectively. The function returns an integer containing the value of the length of the LCS of str1 and str2. For instance, the function may be called as lcs(.
Another function max( is also used. The function takes two integers a and b as arguments. It compares these two integers and returns the integer value of whichever is the maximum between a and b.
Answer group
Explanation
A: n - 1, B: n — on a mismatch, drop the last character of one string at a time: from str2 in the first call, from str1 in the second.
When the m-th character of str1 and the n-th character of str2 differ, they cannot both end the common subsequence, so at least one of them is discarded. The LCS is the larger of two smaller problems: str1 whole against str2 without its last character, lcs( (blank A), and str1 without its last character against str2 whole, lcs( (blank B). Each call shrinks one index by 1, so the recursion reaches the base case m = 0 or n = 0.
Example: in lcs(, Z and D differ, so the result is the larger of the LCS of ABXDZ and ABC (2, "AB") and the LCS of ABXD and ABCD (3, "ABD"), which is 3.
Answer (c)
Why not others:
- •(a) and (b) — A as
nmakes the first calllcs(, the same arguments as the current call, so the recursion never ends; in addition (a)'s B drops both characters at once and (b)'s B steps past the end ofstr1, str2, m, n) str2 - •(d) — A is right, but B as
n + 1points beyond the end ofstr2instead of keeping it whole - •(e) and (f) — A as
n + 1points beyond the end ofstr2on the very first call and moves away from the base casen = 0instead of towards it
Key rule: Every recursive call must shrink the problem toward the base case; in LCS the mismatch case tries both "drop one last character" subproblems and keeps the larger result.
String Processing · AI-written, may contain errors
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.