ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
def lcsub(a, b):
    best = end = 0
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
                if dp[i][j] > best:
                    best = dp[i][j]
                    end = i
    return a[end - best:end]
print(lcsub('abcdxyz', 'xyzabcd'), lcsub('zxabcd', 'abcdzx'))
  1. A. abcd abcd
  2. B. xyz abcd
  3. C. abcd zx
  4. D. abcd dcba

Correct answer: A. abcd abcd

The longest common substring is found by a DP table that tracks the run length ending at each pair of positions. Both pairs of strings share the substring abcd, which has length 4.

More Python Programming questions

Exams that ask this topic