⚠️ This visualization was AI-generated and may contain inaccuracies. Please verify against the original LeetCode problem (#131) before relying on it.

Palindrome Partitioning

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

Backtracking LeetCode 131 ↗ Medium

Problem

Input: A string s

Output: All possible palindrome partitionings

Example:

  • Input: s = "aab"
  • Output: [["a","a","b"],["aa","b"]]

Constraints:

  • 1 ≤ s.length ≤ 16
  • s contains only lowercase English letters

Interactive Visualization

800ms
String & Current Partition
Palindrome Check: -
Current Partition
Empty
Valid Partitions Found: 0
Code
fun partition(s: String): List<List<String>> {    val result = mutableListOf<List<String>>()    fun isPalindrome(sub: String): Boolean {        return sub == sub.reversed() }    fun backtrack(start: Int, current: MutableList<String>) {        if (start == s.length) {            result.add(ArrayList(current))            return }        for (end in start + 1..s.length) {            val substring = s.substring(start, end)            if (isPalindrome(substring)) {                current.add(substring)                backtrack(end, current)                current.removeAt(current.size - 1)    }   }   }    backtrack(0, mutableListOf())    return result }
Status
Ready to start

How It Works

Key Insight

Use backtracking to explore all possible ways to partition the string. At each position, try all possible substrings starting from that position. If a substring is a palindrome, add it to the current partition and recursively partition the remaining string.

Algorithm Steps

  1. Initialize: Create an empty result list and start backtracking from position 0 with an empty partition
  2. Base Case: If we've reached the end of the string, we have a valid partition - add it to results
  3. Try All Splits: For each possible end position from current start, extract substring
  4. Check Palindrome: If substring is a palindrome, add it to current partition
  5. Recurse: Continue partitioning from the end position with updated partition
  6. Backtrack: Remove the last added substring and try the next possibility
  7. Return: All collected valid partitions

Complexity Analysis

Metric Complexity Explanation
Time O(n·2^n) In worst case, we have 2^n possible partitions and checking each partition takes O(n) time
Space O(n) Recursion stack depth is at most n (length of string)