I am solving an interview practice question:
Partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
My solution is as below, and was accepted.
def partition(self, s: str) -> List[List[str]]:
ans = []
def bt(w, curr):
if not w:
ans.append(curr)
else:
for l in range(1, len(w)+1):
chunk = w[:l]
if ''.join(reversed(chunk)) != chunk:
continue
bt(w[l:], curr + [chunk])
bt(s, [])
return ans
The time complexity given in the solutions is O(N * 2^N) I do not understand that.
I understand that:
- there are 2^(N-1) possible partitions,
- in the worst case any partition yields palindromes,
- checking for palindrome is linear in the size of the input.
But I am struggling to estimate the amount of work done in the for loop. Why are we multiplying 2^N with just N? What about the linear amount of work done within the body of the loop?
Any insight/hints would be helpful. In conjunction with this, I am unable to write a recurrence relation ..
Thank you very much!!