← Meta (Facebook) bank

Meta (Facebook) · Question 15 · Strings

Longest Palindromic Substring

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

Problem

You are given a string. Find the longest palindromic substring.

Approach

Expand around every center and keep the longest palindrome.

Time O(n²)Space O(1)

How it works

  1. 1Try odd and even centers everywhere.
  2. 2Expand while characters mirror.
  3. 3Remember the longest span.

Sample input / output

Input:
forgeeksskeegfor
Output:
geeksskeeg

Constraints

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

Solution — read it, then walk it

Time O(n²)Space O(1)Loops 2Branches 2Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesno↻ repeatyesnoSTARTsstart = 0maxLen = 0DEFINE expand(left, right)nonlocal start, maxLenwhile left >= 0 andright < len(s) ands[left] == s[right]left -= 1right += 1if right - left - 1 >maxLenmaxLen = right - left - 1start = left + 1for i in range(len(s))expand(i, i)expand(i, i + 1)RETURN s[start:start +maxLen]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