Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Subsets With Duplicates (easy)
Problem Statement
Given a set of numbers that might contain duplicates, find all of its distinct subsets.
Example 1:
Input: [1, 3, 3]
Output: [], [1], [3], [1,3], [3,3], [1,3,3]
Example 2:
Input: [1, 5, 3, 3]
Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3], [3,3], [1,3,3], [3,3,5], [1,5,3,3]
Constraints:
1 <= nums.length <= 10-10 <= nums[i] <= 10
Try it yourself
Try solving this question here:
.....
.....
.....
Like the course? Get enrolled and start learning!
Mohammed Dh Abbas
· 2 years ago
class Solution: def findSubsets(self, nums): nums.sort() subsets = [[]] temp = [] prev_count = 0 # loop through each number for index, num in enumerate(nums): # for non duplicate case. clone previous subsets and append num to each if index == 0 or (index > 0 and nums[index] != nums[index - 1]): for subset in subsets: clone = subset[:] clone.append(num) temp.append(clone) # for duplicate case. clone the subsets from the point of prev_count and append num to each else: for j in range(len(subsets) - prev_count, len(subsets)): clone = list(subsets[j]) clone.append(num) temp.append(clone) # add the new items to the