Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: What is the length of the longest palindromic substring of 'abacdcaba'? Run the code.

Problem: What is the length of the longest palindromic substring of 'abacdcaba'? Run the code.
s = 'abacdcaba'
best = 0
for c in range(2 * len(s) - 1):
    l, r = c // 2, c // 2 + c % 2
    while l >= 0 and r < len(s) and s[l] == s[r]:
        l -= 1
        r += 1
    best = max(best, r - l - 1)
print(best)
What is printed?
  1. A. 11
  2. B. 9
  3. C. 7
  4. D. 3

Correct answer: B. 9

Expanding around the centre 'd' reaches both ends, so the whole string (length 9) is a palindrome. Using r − l + 1 after the loop gives 11, the inner "bacdcab" is 7, and "aba" is 3.

More Coding Interview Problems questions

Exams that ask this topic