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
26 changes: 26 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// https://leetcode.com/problems/subsets/
// Time Complexity : O(2^n) where n is the number of elements in the input array.
// This is because for each element, we have two choices:
// either include it in the subset or exclude it.
// Therefore, the total number of subsets is 2^n.
// Space Complexity : O(2^n) for storing all the subsets.
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

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

private void helper(int[] nums, int pivot, List<Integer> path, List<List<Integer>> result){
result.add(new ArrayList<>(path));

for( int i = pivot; i < nums.length; i++){
path.add(nums[i]);
helper(nums, i+1, path, result);
path.remove(path.size()-1);
}
}
}
48 changes: 48 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// https://leetcode.com/problems/palindrome-partitioning/
// Time Complexity : O(n* 2^n) where n is the length of the input string.
// This is because in the worst case, we can have 2^n possible partitions of the string,
// and for each partition, we need to check if it is a palindrome, which takes O(n) time.
// Space Complexity : O(n^ 2) where n is the length of the input string.
// This is because we need to store all possible partitions,
// and each partition can have up to n strings of length up to n.
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No

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

private void helper(String s, List<String> path, List<List<String>> result){
// base case
if(s.length() == 0){
result.add(new ArrayList<>(path));
return;
}
//logic
for(int i = 0; i< s.length(); i++){
String currStr = s.substring(0, i+1);
if(isPalindrome(currStr)){
//action
path.add(currStr);
//recurse
helper(s.substring(i+1), path, result);
//backtrack
path.remove(path.size() -1);
}
}

}
private boolean isPalindrome(String s){
int i = 0;
int j = s.length() - 1;
while(i<j){
if(s.charAt(i++) != s.charAt(j--)){
return false;
}
}
return true;
}
}