← Google bank

Google · Question 17 · Strings

Longest Palindromic Substring

StringsPythoncode⏱ O(n²)💾 O(1)
Product-based

Problem

Find the longest palindromic substring in a given string.

Approach

Expand around center for all positions.

Time O(n²)Space O(1)

How it works

  1. 1Define a helper to expand around a center while it stays a palindrome.
  2. 2Check odd-length and even-length centers.
  3. 3Update the longest palindrome indices.
  4. 4Return the substring based on the recorded indices.

Sample input / output

Input:
babad
Output:
bab

Constraints

1 <= s.length <= 1000; s consists of digits and English letters.

Solution — read it, then walk it

Time O(n²)Space O(1)Loops 2Branches 3Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesnoyes↻ repeat↻ repeatyesnoSTARTsDEFINE expand(left, right)while left >= 0 andright < len(s) ands[left] == s[right]left -= 1right += 1RETURN left + 1, right - 1start = end = 0for i in range(len(s))l1, r1 = expand(i, i)l2, r2 = expand(i, i + 1)if r1 - l1 > end -startstart, end = l1, r1if r2 - l2 > end -startstart, end = l2, r2RETURN s[start:end + 1]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)s = next(it)print(longestPalindrome(s))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/24

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits