CodeArchon

mediumBacktrackingAmazonGoogle

Palindrome Partitioner

A linguistic analyzer segments a text into contiguous slices that each read the same forwards and backwards.

Given a string s, partition it such that every substring is a palindrome. Return all possible partitions.

Choose approach

a
0
ij
a
1
b
2
SetPalindromic partitions (0)
empty
1/7
Narrationstep 1 of 7

Pick palindrome "a".

1def partition(s):
2 out, cur = [], []
3 def isPal(l, r):
4 while l < r:
5 if s[l] != s[r]: return False
6 l += 1; r -= 1
7 return True
8 def dfs(i):
9 if i == len(s):
10 out.append(cur[:]); return
11 for j in range(i, len(s)):
12 if isPal(i, j):
13 cur.append(s[i:j+1]); dfs(j+1); cur.pop()
14 dfs(0); return out
Variables
cur=[a]
out=0

How to think about it

  1. Palindrome check: two pointers from both ends.
  2. Only recurse on palindromic prefixes -> prune non-palindrome branches.
  3. Emit the current list when we consume the entire string.

Edge cases to catch in interview

  • Single character -> itself is a palindrome.
  • All identical chars -> every slice is a palindrome.

Examples

Example 1[["a","a","b"],["aa","b"]]
{"s":"aab","values":["a","a","b"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed