Bird
Raised Fist0
Interview PrepbacktrackingmediumAmazonGoogleFacebook

Palindrome Partitioning

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
</>
IDE
def partition(s: str) -> list:public List<List<String>> partition(String s)vector<vector<string>> partition(string s)function partition(s)
def partition(s):
    # Write your solution here
    pass
class Solution {
    public List<List<String>> partition(String s) {
        // Write your solution here
        return new ArrayList<>();
    }
}
#include <vector>
#include <string>
using namespace std;

vector<vector<string>> partition(string s) {
    // Write your solution here
    return {};
}
function partition(s) {
    // Write your solution here
}
0/10
Common Bugs to Avoid
Wrong: [["a","b","b","a"]]Only returned one partition instead of all possible partitions.Ensure backtracking explores all substring splits and collects all valid partitions, not just one.
Wrong: [["a","a","b"]]Missed longer palindrome substrings like 'aa'.Check all substring lengths and include substrings that are palindromes, not just single characters.
Wrong: [["a","b","a","a","b","a"]]Greedy approach picking only smallest palindromes, missing longer nested palindromes.Backtrack by exploring all substring lengths at each step, not just the smallest or largest.
Wrong: []Returned empty list for non-empty input due to missing base case or incorrect recursion.Add base case to add current path to result when start index reaches string length.
Wrong: [["a","b","c"],["abc"]]Incorrect palindrome check allowing non-palindromic substrings like 'abc'.Implement strict palindrome check function that returns false for non-palindromes.
Test Cases
t1_01basic
Input{"s":"aab"}
Expected[["a","a","b"],["aa","b"]]

The string 'aab' can be partitioned into palindromes as ['a','a','b'] and ['aa','b'].

t1_02basic
Input{"s":"racecar"}
Expected[["r","a","c","e","c","a","r"],["r","a","cec","a","r"],["r","aceca","r"],["racecar"]]

The string 'racecar' has multiple palindrome partitions including single letters and longer palindromes like 'cec', 'aceca', and 'racecar'.

t2_01edge
Input{"s":""}
Expected[[]]

Empty string has no partitions, so result is an empty list.

t2_02edge
Input{"s":"z"}
Expected[["z"]]

Single character string 'z' has only one palindrome partition: itself.

t2_03edge
Input{"s":"aaaa"}
Expected[["a","a","a","a"],["a","a","aa"],["a","aa","a"],["a","aaa"],["aa","a","a"],["aa","aa"],["aaa","a"],["aaaa"]]

String with all identical characters 'aaaa' has multiple palindrome partitions with varying substring lengths.

t2_04edge
Input{"s":"abc"}
Expected[["a","b","c"]]

String with no palindromic substrings longer than 1 results in partitions of single characters only.

t3_01corner
Input{"s":"abaaba"}
Expected[["a","b","a","a","b","a"],["a","b","a","aba"],["a","b","aa","b","a"],["a","baab","a"],["aba","a","b","a"],["aba","aba"],["abaaba"]]

Complex palindrome partitions including nested palindromes like 'aba', 'aa', 'baab'.

t3_02corner
Input{"s":"abba"}
Expected[["a","b","b","a"],["a","bb","a"],["abba"]]

Tests correct handling of even-length palindrome 'bb' and full palindrome 'abba'.

t3_03corner
Input{"s":"abcba"}
Expected[["a","b","c","b","a"],["a","bcb","a"],["abcba"]]

Tests palindrome partitions including odd length palindrome 'bcb' and full palindrome 'abcba'.

t4_01performance
Input{"s":"aaaaaaaaaaaaaaaa"}
⏱ Performance - must finish in 2000ms

Input string of length 16 with all identical characters. Algorithm must run in O(N*2^N) time within 2 seconds.

Practice

(1/5)
1. Examine the following buggy code snippet for Expression Add Operators. Which line contains the subtle bug that causes incorrect results on inputs with leading zeros?
def addOperators(num: str, target: int) -> List[str]:
    res = []
    path = []
    def backtrack(index: int, evaluated: int, last_operand: int):
        if index == len(num):
            if evaluated == target:
                res.append(''.join(path))
            return
        for i in range(index, len(num)):
            # Bug: missing leading zero check
            curr_str = num[index:i+1]
            curr = int(curr_str)
            length_before = len(path)
            if index == 0:
                path.append(curr_str)
                backtrack(i+1, curr, curr)
                path[length_before:] = []
            else:
                path.append('+'); path.append(curr_str)
                backtrack(i+1, evaluated + curr, curr)
                path[length_before:] = []
    backtrack(0, 0, 0)
    return res
medium
A. Line with 'if i != index and num[index] == '0':' missing here
B. Line with 'curr_str = num[index:i+1]' (substring extraction)
C. Line with 'path[length_before:] = []' (backtracking cleanup)
D. Line with 'path.append('+'); path.append(curr_str)' (operator insertion)

Solution

  1. Step 1: Identify handling of leading zeros

    The code lacks the check 'if i != index and num[index] == '0': break' which prevents invalid operands like "05".
  2. Step 2: Confirm bug location

    This missing check is critical and should be placed before parsing curr_str to avoid invalid expressions.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing leading zero check causes invalid operands [OK]
Hint: Leading zero check missing causes invalid operands [OK]
Common Mistakes:
  • Confusing backtracking cleanup lines as bug
  • Thinking substring extraction is buggy
2. Consider the following buggy code for generating letter combinations. Which line contains the subtle bug that causes incorrect or incomplete results?
from collections import deque

def letterCombinations(digits):
    if digits == '':
        return ['']
    digit_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
                 '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
    queue = deque([''])
    for digit in digits:
        letters = digit_map[digit]
        for _ in range(len(queue)):
            prev = queue.popleft()
            for char in letters:
                queue.append(prev + char)
    return list(queue)
medium
A. Line 7: letters = digit_map[digit]
B. Line 2: if digits == '': return ['']
C. Line 10: prev = queue.popleft()
D. Line 1: from collections import deque

Solution

  1. Step 1: Analyze empty input handling

    Returning [''] for empty input is incorrect; the problem expects an empty list [] when input is empty.
  2. Step 2: Check other lines

    Digit mapping, queue operations, and imports are correct and do not cause bugs.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Empty input should return [] not [''] to match problem spec [OK]
Hint: Empty input must return empty list, not list with empty string [OK]
Common Mistakes:
  • Returning [''] instead of [] for empty input
  • Assuming digits '1' or '0' map to letters
3. The following code attempts to generate all permutations of a list using Heap's algorithm but contains a subtle bug:
def permute(nums):
    res = [nums[:]]
    c = [0] * len(nums)
    i = 0
    while i < len(nums):
        if c[i] < i:
            if i % 2 == 0:
                nums[0], nums[i] = nums[i], nums[0]
            else:
                nums[c[i]], nums[i] = nums[i], nums[c[i]]
            res.append(nums)
            c[i] += 1
            i = 0
        else:
            c[i] = 0
            i += 1
    return res
What is the bug in this code?
medium
A. The used array c is not reset properly, causing infinite loop
B. Appending nums directly without copying causes all entries in res to reference the same list
C. Swapping nums[0] and nums[i] when i is even is incorrect logic
D. The initial res list should be empty, not contain nums[:] at start

Solution

  1. Step 1: Identify how results are stored

    The code appends nums directly to res without copying.
  2. Step 2: Understand consequences of appending references

    Since nums is mutated in-place, all entries in res point to the same list, resulting in duplicates of the final permutation.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Appending a copy nums[:] fixes the bug [OK]
Hint: Always append a copy of mutable lists to results [OK]
Common Mistakes:
  • Forgetting to copy before appending results in duplicate references
4. What is the time complexity of the optimal iterative backtracking solution with pruning for restoring IP addresses from a string of length n, and why?
medium
A. O(3^4) because each of the 4 segments can be length 1 to 3, and pruning limits exploration
B. O(4^n) because each character can start a new segment or continue the previous one
C. O(n^4) because we try all partitions of the string into 4 segments
D. O(n!) due to permutations of segment lengths

Solution

  1. Step 1: Identify branching factor per segment

    Each segment can be length 1, 2, or 3, so branching factor is at most 3 per segment.
  2. Step 2: Calculate total combinations

    There are 4 segments, so total combinations are at most 3^4 = 81. Pruning further reduces this.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Time complexity depends on fixed 4 segments with max 3 choices each [OK]
Hint: Fixed 4 segments with max 3 lengths each -> 3^4 complexity [OK]
Common Mistakes:
  • Assuming complexity depends on n^4
  • Confusing permutations with combinations
5. Suppose you want to generate all permutations of an array where elements can be repeated any number of times (i.e., unlimited reuse of elements). Which modification to the standard backtracking approach is correct?
hard
A. Remove the used array entirely and allow elements to be chosen multiple times at each recursion level
B. Use the same backtracking with a used array but reset used[i] to false only after the entire recursion finishes
C. Use in-place swapping but skip swapping elements that have been used before in the current recursion path
D. Generate permutations normally and then filter out duplicates after generation

Solution

  1. Step 1: Understand the problem variant

    Elements can be reused unlimited times, so no need to track usage.
  2. Step 2: Modify backtracking accordingly

    Removing the used array allows choosing any element at each recursion level multiple times, generating permutations with repetition.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Allowing repeated choices without usage tracking fits unlimited reuse [OK]
Hint: Unlimited reuse means no used array needed [OK]
Common Mistakes:
  • Keeping used array causes missing permutations or incorrect pruning