ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
def pal_sub(s):
    n = len(s)
    best = ''
    for c in range(2 * n - 1):
        l, r = c // 2, c // 2 + c % 2
        while l >= 0 and r < n and s[l] == s[r]:
            l -= 1
            r += 1
        if r - l - 1 > len(best):
            best = s[l + 1:r]
    return best
print(pal_sub('babad'), pal_sub('cbbd'))
  1. A. aba bb
  2. B. bab b
  3. C. bab bb
  4. D. cbbd bb

Correct answer: C. bab bb

Expanding around each centre keeps the first palindrome of maximum length. bab is found before aba, and a later palindrome must be strictly longer to replace it.

More Python Programming questions

Exams that ask this topic