Uber | Phone Interview | Subsets without distinct pairs of elements
Anonymous User
1327

You are given inputs N and pairs where N is an integer and pairs is a list of pairs that cannot be in the same subset.

You are asked to count the number of unique/sorted subsets created from the range 1 to N (inclusive) that do not contain any of the pairs found in the list "pairs".

For example:

Input : ( 4, [(1, 3), (2, 4)] )
Output : 7

Explanation:
N = 4 so all the possible subsets are 
[(1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4), (1,2,3,4)].

Since Pairs = [(1, 3), (2, 4)], any subsets containing 1 and 3 or 2 and 4 cannot be counted. 
Therefore, the final valid subsets are
[(1), (2), (3), (4), (1,2), (2,3), (3,4)]

I attempted a brief brute force solution by constructing the power set of the range 1 to N + 1 ([(1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4), (1,2,3,4)]) and then going through each pair in pairs and checking to see if all its elements were in the power set.

However, this solution is too slow and I wasn't sure on what method I could use to solve this in a faster time. Would really appreciate if someone had a solution or similar problem they could point me to.

Comments (5)