Post

Leetcode 131. Palindrome Partitioning

Explanation for Leetcode 131 - Palindrome Partitioning, and its solution in Python.

Problem

Leetcode 131 - Palindrome Partitioning

Example:

1
2
3
4
5
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]

Input: s = "a"
Output: [["a"]]

Approach

We can solve this problem by using DFS and checking if the string is a palindrome with a helper function

Since we want separate array for different level (meaning how many characters) we can do this for each loop

Here is the Python code for the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def partition(self, s: str) -> List[List[str]]: 
        res = []
        part = []

        def dfs(i):
            if i >= len(s):
                res.append(part.copy())
                return
            
            for j in range(i, len(s)):
                if self.check(s, i, j):
                    part.append(s[i:j+1])
                    dfs(j+1)
                    part.pop()
        
        dfs(0)
        return res
    
    def check(self, s, l, r):
        while l < r:
            if s[l] != s[r]:
                return False
            l, r = l+1, r-1
        return True

Time Complexity and Space Complexity

Time Complexity: $O(n*2^n)$

Space Complexity: $O(n*2^n)$

This post is licensed under CC BY 4.0 by the author.