Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Solution
AlgoMonster Solution
This can be Tree Pruning question. In terms of our template, we have:
is_leaf()
: We can check this by seeing if the starting index we’re operating from is the same as the length of the stringget_edges()
: The possible next prefixes are obtained by substringstart
toend
, where we iterate through possiblefor end in range(start + 1, n + 1)
is_valid()
: Theprefix
must be a palindrome- Increment index by the length of the
prefix
, which is justend
Notes:
path[:]
is used to make a copy
NeetCode Solution
This is very similar to the above, except it uses a global variable instead of a state. Instead of passing path
as an argument in dfs()
, we just have a global part[]
variable.
Complexity
Time complexity for both above is :
- For each letter in the input string, we can either include it as a previous string or start a new string with it. With those two choices, the total number of operations is .
- We also need operations to check if the string is a palindrome.
Space complexity depends on the height of the tree; in the worst case, it’s .
- Maximum amount of memory used at any time is proportional to the maximum depth of the recursive call stack