0

Question (Leetcode 131; https://leetcode.com/problems/palindrome-partitioning/) Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

The runtime to this problem is stated to be O(2^n * n), but this seems like an extremely loose upper bound if you use memoization to store all previously created substrings.

I don't know how to determine the tight upper bound time complexity for such a problem, using my implementation. My own guess is that since there are only n^2 possible substrings, each of max n length, you have n^3 work spread across the 2^(n-1) max possible leaf nodes. But I don't know what this looks like in Big-O notation, or if it's even right. How do people normally go about determining the upper bound time complexity for an implementation such as mine? I'm specifically curious about finding the time complexity of my specific approach to the problem, since it utilizes a backtracking approach which I've always had difficulty determining the tight upper bound for.

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        # backtracking solution 
        @cache
        def isPalindrome(startIdx, endIdx):
            tmp1, tmp2 = startIdx, endIdx
            while startIdx < endIdx:
                if s[startIdx] != s[endIdx]:
                    return False
                startIdx += 1
                endIdx -= 1
            return s[tmp1: tmp2 + 1]
    def recursivelyDeterminePartitions(startIdx):
        if startIdx == n:
            res.append(currPartition.copy())
            return 

        for i in range(startIdx, n):
            if (substring := isPalindrome(startIdx, i)):
                currPartition.append(substring)
                recursivelyDeterminePartitions(i+1)
                currPartition.pop()

    res = []
    currPartition = []
    n = len(s)
    recursivelyDeterminePartitions(0)
    return res

Sid S
  • 1
  • 1

0 Answers0