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
44 changes: 44 additions & 0 deletions PalindromePartitioning.kt
Original file line number Diff line number Diff line change
@@ -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<List<String>>()
fun partition(s: String): List<List<String>> {
val path = mutableListOf<String>()
helper(s, 0, path)
return result
}

fun helper(s:String, pivot: Int, path: MutableList<String>) {
//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
}
}
29 changes: 29 additions & 0 deletions Subsets.kt
Original file line number Diff line number Diff line change
@@ -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<List<Int>>()
fun subsets(nums: IntArray): List<List<Int>> {
val path = mutableListOf<Int>()
helper(nums, 0, path)
return result
}
fun helper(nums: IntArray, i: Int,path: MutableList<Int>) {
//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)
}
}