diff --git a/palindrome-partitioning.py b/palindrome-partitioning.py new file mode 100644 index 00000000..5d1cff5f --- /dev/null +++ b/palindrome-partitioning.py @@ -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 \ No newline at end of file diff --git a/subsets.py b/subsets.py new file mode 100644 index 00000000..3c9c84a8 --- /dev/null +++ b/subsets.py @@ -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 + + + \ No newline at end of file