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
38 changes: 38 additions & 0 deletions palindrome-partitioning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#--------Solution 1 : For loop based recursion------------
''' Time Complexity : O(n* 2^n)) ; n = len of the list and O(n) to palindrome check
Space Complexity : O(n^2) : recursion stack + substring creation
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''

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

def helper(s, pivot, path):
#base
if pivot == len(s):
self.result.append(list(path))

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

helper(s,0,[])
return self.result

def isPalindrome(self, sub):
l, r = 0, len(sub)-1
while l < r:
if sub[l] != sub[r]:
return False
l += 1
r -= 1
return True
47 changes: 47 additions & 0 deletions subsets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#--------Solution 1 : Backtraking------------
''' Time Complexity : O(n* 2^n)) ; n = len of the list and O(n) to copy path to result
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
self.result = []

def helper(nums, idx, path):
#base
if idx == len(nums):
self.result.append(list(path))
return
#logic
#no choose
helper(nums, idx+1, path)

#choose
path.append(nums[idx])
helper(nums, idx+1, path)
#backtrack
path.pop()

helper(nums,0,[])
return self.result

#--------Solution 2 : Nested For loop------------
''' Time Complexity : O(n * n^2)) ;
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No
'''
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result =[[]]

for i in range(len(nums)):
for j in range(len(result)):
li = result[j].copy()
li.append(nums[i])
result.append(li)
return result