← Recursion & DP

Micro-Drill #159 — Longest Palindromic Substring

Recursion & DP Target: 15s

Expand around center: try each index as center for odd and even palindromes. O(n²) time, O(1) space.

def longestPalindrome(s):
    res = ""
    for i in range(len(s)):
        # odd length
        l, r = i, i
        while l >= 0 and r < len(s) and s[l] == s[r]:
            if r - l + 1 > len(res):
                res = s[l:r+1]
            l -= 1; r += 1
        # even length
        l, r = i, i + 1
        while l >= 0 and r < len(s) and s[l] == s[r]:
            if r - l + 1 > len(res):
                res = s[l:r+1]
            l -= 1; r += 1
    return res

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #158 Micro #160 →