Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions PalindromePartitioning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Time Complexity : O(2^n * n) -> For n length string, exponential partitions × (palindrome checks + creating substrings)
# Space Complexity : O(n^2) (substring creation and recursion stack)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : We start at the first index and keep trying all substrings from that point.
# Whenever we find a palindrome substring, we add it and recurse from the next index.
# Once we reach the end, we save the current list, and then backtrack to try other splits.

class Solution:
def partition(self, s: str) -> List[List[str]]:
self.res = []
self.helper(s, 0, [])
return self.res

def helper(self, s, pivot, path):
if pivot == len(s):
self.res.append(list(path))
return

for i in range(pivot, len(s)):
subStr = s[pivot:i+1]
if self.isPalindrome(subStr):
path.append(subStr)
self.helper(s, i+1, path)
path.pop()

def isPalindrome(self, s):
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True

22 changes: 22 additions & 0 deletions Subsets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Time Complexity : O(n × 2^n) - 2^n subsets × up-to-n cost to copy path into the result list
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : We iterate from the current pivot and add each element one by one into the path.
# For every choice, we recurse forward and then backtrack to explore other paths.
# We save a copy of the current list at every level to record all subsets.

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
self.res = []
self.path = []
self.helper(nums, 0)
return self.res

def helper(self, nums, pivot):
self.res.append(self.path[:])
for i in range(pivot, len(nums)):
self.path.append(nums[i])
self.helper(nums, i+1)
self.path.pop()