Problem statement

https://binarysearch.com/problems/Longest-Palindromic-Substring/

Solution

Equal to Leetcode 0005. Longest Palindromic Substring.

Complexity

It is O(n^2) time for this solution and O(1) for space.

Code

class Solution:
    def solve(self, s):
        n, ans = len(s), 0
        def helper(i, j):
            while i >= 0 and j < n and s[i] == s[j]:
                i, j = i - 1, j + 1
            return j - i - 1
        
        for k in range(n):
            ans = max(helper(k, k), helper(k, k + 1), ans)
        return ans