diff --git a/PalindromePartitioning.kt b/PalindromePartitioning.kt new file mode 100644 index 00000000..83af97d1 --- /dev/null +++ b/PalindromePartitioning.kt @@ -0,0 +1,44 @@ +// In this problem, we are using for loop based backtracking to find all possible palindrome partitioning of a given string. We maintain a path that represents the current partition being constructed. +// At each step, we explore if the substring from the current pivot to the current index is a palindrome or not. If it is we add it to path and recursively call the helper with updated pivot. +// When we reach the end of the string, we add the current path to our result list. +// Time complexity: O(n * 2^n) where n is the length of the string and 2^n is the no. of possible partitions +// Space complexity : O(n) + +class Solution { + val result = mutableListOf>() + fun partition(s: String): List> { + val path = mutableListOf() + helper(s, 0, path) + return result + } + + fun helper(s:String, pivot: Int, path: MutableList) { + //base + if(pivot == s.length) { + result.add(path.toList()) + return + } + + for(i in pivot until s.length) { + val subStr = s.substring(pivot, i+1) + if(isPalindrome(subStr)) { + path.add(subStr) + + helper(s, i + 1, path) + + path.removeAt(path.lastIndex) + } + } + } + + fun isPalindrome(s: String) : Boolean { + var left = 0 + var right = s.length - 1 + while(left < right) { + if(s[left] != s[right]) return false + left++ + right-- + } + return true + } +} \ No newline at end of file diff --git a/Subsets.kt b/Subsets.kt new file mode 100644 index 00000000..2a5385f6 --- /dev/null +++ b/Subsets.kt @@ -0,0 +1,29 @@ +// In this problem, we need to find all possible subsets of a given set of integers. We are using backtracking to explore all combinations. We maintain a path that represents the current subset being constructed. +//At each step, we have the choice to either include or exclude the current element. When we reach the end of the array, we add the current path to our result list. +// Time complexity: O(n * 2^n) where n is the number of elements and 2^n is the no. of substes + // Space complexity : O(n) +class Solution { + val result = mutableListOf>() + fun subsets(nums: IntArray): List> { + val path = mutableListOf() + helper(nums, 0, path) + return result + } + fun helper(nums: IntArray, i: Int,path: MutableList) { + //base + if(i == nums.size) { + result.add(path.toList()) + return + } + + //no choose + helper(nums, i + 1, path) + //choose + //action + path.add(nums[i]) + //recurse + helper(nums, i+ 1, path) + //backtrack + path.removeAt(path.size - 1) + } +} \ No newline at end of file