diff --git a/PalindromePartitions.swift b/PalindromePartitions.swift new file mode 100644 index 00000000..db9b7fdc --- /dev/null +++ b/PalindromePartitions.swift @@ -0,0 +1,61 @@ +// +// PalindromPartitions.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 4/7/26. +// + +class PalindromePartition { + + init() { + + } + + /* + time complexity - n * 2^n (since at every position, we have choice to choose or not choose so, exponent of 2.) We are checking for each and every string if it is palindrome or not. Hence, multiple by n + */ + func partition(_ s: String) -> [[String]] { + var result = [[String]]() + var path = [String]() + let sArr = Array(s) + helper(sArr: sArr, start: 0, path: &path, result: &result) + return result + } + + //for loop based recursion + func helper(sArr: [Character], start: Int, path: inout [String], result: inout [[String]]) { + + //base + //if we reached end of string then add in the result + if (start == sArr.count) { + result.append(path) + return + } + + for i in start.. Bool { + var i = 0 + var j = sArr.count - 1 + while (i < j) { + if (sArr[i] == sArr[j]) { + i += 1 + j -= 1 + } else { + return false + } + } + return true + } + +} diff --git a/Subsets.swift b/Subsets.swift new file mode 100644 index 00000000..5179adc3 --- /dev/null +++ b/Subsets.swift @@ -0,0 +1,95 @@ +// +// Subsets.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 4/7/26. +// + +class Subsets { + + init() { + + } + + //using 0-1 recursion + /* + time complexity - 2^n + n - no of elements in array + */ + func subsets(_ nums: [Int]) -> [[Int]] { + var result = [[Int]]() + var path = [Int]() + findSubsets(nums, i: 0, path: &path, result: &result) + return result + } + + private func findSubsets(_ nums: [Int], i: Int, path: inout [Int], result: inout [[Int]]) { + + //base + if (i == nums.count) { + result.append(path) + return + } + + //no choose + findSubsets(nums, i: i + 1, path: &path, result: &result) + + //choose + path.append(nums[i]) + findSubsets(nums, i: i + 1, path: &path, result: &result) + path.removeLast() + } + + //MARK: For-loop based recursion + //using for-loop based recursion + func subsetsUsingForLoop(_ nums: [Int]) -> [[Int]] { + var result = [[Int]]() + var path = [Int]() + findSubsetsUsingForLoop(nums, start: 0, path: &path, result: &result) + return result + } + + /* + In for-loop recursion, every node itself represents a valid subset. We must record subset at each node. Not just leaf nodes. + */ + private func findSubsetsUsingForLoop(_ nums: [Int], start: Int, path: inout [Int], result: inout [[Int]]) { + + //base + result.append(path) + + //logic + for i in start.. [], [1], [2], [3], [1, 2], [2, 3] + then for + + one loop on result + another loop on elements of array. Create deep copy of all the elements inside the result + */ + + func subsetsUsingIterativeApproach(_ nums: [Int]) -> [[Int]] { + var result = [[Int]]() + result.append([]) + for i in 0..