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
33 changes: 33 additions & 0 deletions palindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Time Complexity : O(2^n * n) n: lenght of the string.
# Space complexity :O(N) auxilary space for recursion stack.
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No

# Your code here along with comments explaining your approach
# Iterate through the string starting from a pivot index, generating substrings from pivot to every possible end index i
# If the substring is a palindrome, append it to the path and recursively partition the remaining string starting from i + 1
# Once the pivot reaches the end of the string, append a copy of the path to the results. Then, pop() the last substring to undo the choice and explore other branches.

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

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

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

def isPalindrome(self,s: str) -> bool:
return s == s[::-1]
32 changes: 32 additions & 0 deletions subset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Time Complexity : O(n*2^n) n: number of elements.
# Space complexity :O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : None

# Your code here along with comments explaining your approach
# Traverse a recursive decision tree where at each index having two choices: exclude the current number, or include it.
# When the index reaches the end of the input array current path will be complete, valid subset — copy to results.
# After exploring the "choose", remove the current number from the path to clean the state before the function returns, allowing other branches to use a fresh path.


class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:

self.result = []
path = []

def helper(index:int):
if index == len(nums):
self.result.append(path.copy())
return

#no choose
helper(index+1)

#choose
path.append(nums[index])
helper(index+1)
path.pop()

helper(0)
return self.result