Interview Prep’s Post

LeetCode 𝟕𝟖. 𝐒𝐮𝐛𝐬𝐞𝐭𝐬 (Asked by Reddit, Twitter) 𝐐̲𝐮̲𝐞̲𝐬̲𝐭̲𝐢̲𝐨̲𝐧̲ Given an integer array nums of unique elements, return all possible  subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.   Example 1: Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: Input: nums = [0] Output: [[],[0]] 𝐒̲𝐨̲𝐥̲𝐮̲𝐭̲𝐢̲𝐨̲𝐧̲ 1. initialize the result list and an empty subset list, then start the DFS from index 0. List<List<Integer>> result = new ArrayList<>(); List<Integer> subset = new ArrayList<>(); 2. DFS Recursive Function: Base Case: When the index reaches the length of nums, it means we have considered all elements, so we add the current subset to the result. if(index>=nums.length){ result.add(new ArrayList<>(subset)); return; } Recursive Case: Include Current Element: We add the current element to the subset and proceed to the next element. subset.add(nums[index]); dfs(index+1,nums,subset,result); We backtrack by removing the last added element and proceed to the next element without including the current one. subset.remove(subset.size()-1); dfs(index+1,nums,subset,result); 𝐓̲𝐢̲𝐦̲𝐞̲ ̲𝐚̲𝐧̲𝐝̲ ̲𝐬̲𝐩̲𝐚̲𝐜̲𝐞̲ ̲𝐜̲𝐨̲𝐦̲𝐩̲𝐥̲𝐞̲𝐱̲𝐢̲𝐭̲𝐲̲ The overall time complexity is O(n⋅2^n) 2^n comes from the number of subsets. n comes from the time to create each subset when adding it to the result list. The overall space complexity is O(n⋅2^n) Number of Subsets: There are 2^n subsets. Space for Each Subset: Each (or half of the) subsets can have up to n elements ------------------------------------------------------------------- Resources: NeetCode: https://lnkd.in/gtPrxrCN Greg Hogg: https://lnkd.in/g5Q4sYpz #dsa #coding #programming #leetcode

  • text

To view or add a comment, sign in

Explore topics