Skip to content

Commit f06b3fe

Browse files
Merge pull request #314 from tharun694/question
subset question and approach added in backtracking directory.
2 parents 393eef6 + 94bcf34 commit f06b3fe

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

.idea/misc.xml

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
class Subset{
3+
public static void main(String[]args){
4+
int[]nums={1,2,3};
5+
System.out.println(subsets(nums));
6+
}
7+
static public List<List<Integer>> subsets(int[] nums) {
8+
Arrays.sort(nums);
9+
List<List<Integer>> outer=new ArrayList<>();
10+
List<Integer> internal=new ArrayList<>();
11+
12+
int end=0;
13+
outer.add(internal);
14+
for(int i=0;i<nums.length;i++){
15+
int start=0;
16+
if(i>0&&nums[i-1]==nums[i]){
17+
start=end+1;
18+
}
19+
end=outer.size()-1;
20+
int n=outer.size();
21+
for(int j=start;j<n;j++){
22+
internal=new ArrayList<>(outer.get(j));
23+
internal.add(nums[i]);
24+
outer.add(internal);
25+
}
26+
27+
}
28+
return outer;
29+
}
30+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
# Subsets (Unique Subsets)
3+
4+
## 💡 Idea
5+
Generate all unique subsets from an array that may contain duplicates using an **iterative approach**.
6+
7+
## ⚙️ Approach
8+
1. Sort the array to handle duplicates easily.
9+
2. For each number:
10+
- Copy all existing subsets.
11+
- Add the current number to each copy.
12+
- If it's a duplicate, start from the last new subsets only.
13+
14+
## ⏱️ Complexity
15+
- **Time:** O(N × 2^N)
16+
- **Space:** O(N × 2^N)
17+
18+
## 🧩 Example
19+
Input: `[1,2,2]`
20+
Output: `[[], [1], [2], [1,2], [2,2], [1,2,2]]`;

0 commit comments

Comments
 (0)