← Uber bank

Uber · Question 71 · Backtracking

Palindrome Partitioning

BacktrackingPythoncode⏱ O(2^n)💾 O(n²)
Product-based

Problem

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

Approach

Backtracking + precomputed DP table to quickly check if substrings are palindromes.

Time O(2^n)Space O(n²)

How it works

  1. 1Precompute which substrings are palindromes.
  2. 2DFS cuts only at palindrome boundaries.

Sample input / output

Input:
aab
Output:
[['a', 'a', 'b'], ['aa', 'b']]

Constraints

1 <= s.length <= 16; lowercase letters only.

Solution — read it, then walk it

Time O(2^n)Space O(n²)Loops 3Branches 3Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatyesnoyes↻ repeat↻ repeatyesnoSTARTsres = []n = len(s)dp = [[False] * n for _ inrange(n)]for i in range(n - 1,-1, -1)for j in range(i, n)dp[i][j] = (s[i] == s[j])and (j - i < 2 or dp[i +1][j - 1])path = []DEFINE dfs(start)if start == nres.append(path.copy())RETURNfor end inrange(start, n)if dp[start][end]path.append(s[start:end +1])dfs(end + 1)path.pop()dfs(0)RETURN resDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)s = next(it)print(partition(s))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/28

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