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
43 changes: 43 additions & 0 deletions PalindromePartitioning.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution {
/*
TC - O(n * 2^n) -
n is the length of the input string,
2^n is the number of possible partitions, and n is for copying the list to the result
SC - O(n) - for the recursion stack
Solution uses backtracking to generate all possible palindrome partitions of the string.
Starting from the current pivot index, generate every possible substring s[pivot...i].
If the substring is a palindrome, it is added to the current path, and recursion continues from the next index.
After returning, the substring is removed (backtracking) to explore other paths.
When pivot == s.length(), the entire string has been partitioned, so the current partition is copied into
the result.
*/
List<List<String>> result;
public List<List<String>> partition(String s) {
this.result = new ArrayList<>();
helper(s, new ArrayList<>(), 0);
return result;
}

public void helper(String s, List<String> path, int pivot) {
if (pivot == s.length()) {
result.add(new ArrayList<>(path));
}

for (int i = pivot; i < s.length(); i++) {
String curr = s.substring(pivot, i + 1);
if (isPalindrome(curr)) {
path.add(curr);
helper(s, path, i + 1);
path.remove(path.size() - 1);
}
}
}

private boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i <= j) {
if (s.charAt(i++) != s.charAt(j--)) return false;
}
return true;
}
}
35 changes: 35 additions & 0 deletions Subsets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution {
/*
TC - O(n * 2^n) -
n is the length of the input array,
2^n is the number of subsets, and n is for copying the list to the result
SC - O(n) - for the recursion stack

Solution uses backtracking to generate all possible subsets.
At each index, it makes two recursive choices:
Exclude the current element and recurse.
Include the current element, recurse, then remove it (backtrack) to restore the previous state.
When the recursion reaches the end of the array (index == nums.length),
the current subset is copied and added to the result.
*/
List<List<Integer>> result;

public List<List<Integer>> subsets(int[] nums) {
this.result = new ArrayList<>();
helper(nums, 0, new ArrayList<>());
return result;
}

private void helper(int[] nums, int index, List<Integer> list) {
if (index == nums.length) {
result.add(new ArrayList<>(list));
return;
}

helper(nums, index + 1, list);

list.add(nums[index]);
helper(nums, index + 1, list);
list.remove(list.size() - 1);
}
}