ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
def min_cut(s):
    n = len(s)
    pal = [[False] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(i, n):
            pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1])
    cut = [0] * n
    for j in range(n):
        if pal[0][j]:
            cut[j] = 0
        else:
            cut[j] = min(cut[i - 1] + 1 for i in range(1, j + 1) if pal[i][j])
    return cut[-1]
print(min_cut('aab'), min_cut('abccba'))
  1. A. 2 0
  2. B. 1 1
  3. C. 1 0
  4. D. 0 0

Correct answer: C. 1 0

The table pal marks palindromic substrings, and the DP adds one cut per extra piece. aab needs one cut to give aa and b, while abccba is already a palindrome.

More Python Programming questions

Exams that ask this topic