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 @@
// Time Complexity : O(2^(n) * n) where n is the length of String s.
// Space Complexity : O(n^2)
// Did this code successfully run on Leetcode : Yes
// Approach : I followed for loop recursion with backtracking to get the result. For each substring from pivot to i we each if it is a palindrome and then
// proceed ahead.Once the pivot reaches the end of the string we add it to the result, backtrack it and continue the checks with the rest of the substring.


class Solution {
List<List<String>> result;
public List<List<String>> partition(String s) {
this.result = new ArrayList<>();
helper(s, 0, new ArrayList<>());
return result;
}

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

for(int i=pivot; i<s.length(); i++){
String subStr = s.substring(pivot, i+1);
if(isPalindrome(subStr)){ //check if it is palindrome
path.add(subStr);
helper(s, i+1, path);//recurse
path.remove(path.size() - 1);//backtracking
}
}
}

private boolean isPalindrome(String s){
int start = 0, end = s.length()-1;
while(start < end){
if(s.charAt(start) != s.charAt(end)){
return false;
}
start++;
end--;
}
return true;
}
}
30 changes: 30 additions & 0 deletions Subsets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Time Complexity : O(2^(n)) where n is the length of nums array.
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Approach : I followed 0/1 recursion with backtracking and while the base condition is met, before storing the result we store a deep
// copy of it so that the rest of recursion happens without any issues. In no choose and choose condition, index needs to be increased as we dont need
// duplicates in subsets. Once we find the result or we reach the end of the recursive function, we remove the last element in the path so that it can continue recursion.


class Solution {
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> path){
if(index == nums.length){
result.add(new ArrayList<>(path));//add deep copy to result
return;
}
//don't choose
helper(nums, index+1, path);

//choose
path.add(nums[index]);
helper(nums, index+1, path);//recurse
path.remove(path.size()-1); //backtrack
}
}