Data Structures & AlgorithmsModerateTCS NQT · string round

Problem: Find the longest palindromic substring length of 'forgeeksskeegfor' by expanding around each centre.

Problem: Find the longest palindromic substring length of 'forgeeksskeegfor' by expanding around each centre.
s = 'forgeeksskeegfor'
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. 7
  2. B. 12
  3. C. 4
  4. D. 10

Correct answer: D. 10

The longest palindrome is 'geeksskeeg' of length 10, centred between the double s. Expanding from every centre covers even and odd palindromes in O(n^2) time.

More Coding Interview Problems questions

Exams that ask this topic