ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (length of the longest common SUBSTRING, i.e. contiguous, not subsequence)?

What will be the output of the following pseudocode (length of the longest common SUBSTRING, i.e. contiguous, not subsequence)?
Function lcSubstring(String a, String b)
    Integer m = length(a), n = length(b)
    Integer dp[m+1][n+1] = all zeros
    Integer best = 0
    for (each i from 1 to m)
        for (each j from 1 to n)
            if (a[i-1] == b[j-1])
                dp[i][j] = dp[i-1][j-1] + 1
                best = max(best, dp[i][j])
            end if
        end for
    end for
    return best
End Function

Print lcSubstring("abcdxyz", "xyzabcd")
  1. A. 3
  2. B. 4
  3. C. 7
  4. D. 2

Correct answer: B. 4

The longest contiguous run common to both strings is 'abcd', which has length 4 (it must be contiguous, unlike a subsequence, so the matching stops there even though both strings share all 7 characters overall).

More Pseudocode and Code Tracing questions

Exams that ask this topic