Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings.
Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings.
def subsets(a):
a.sort(); res = 0
def go(i):
nonlocal res
res += 1
for j in range(i, len(a)):
if j > i and a[j] == a[j-1]: continue
go(j + 1)
go(0)
return res
print(subsets([1, 2, 2, 3, 3]))What is printed?- A. 32
- B. 18
- C. 24
- D. 16
Correct answer: B. 18
A distinct multiset chooses 0–1 copies of 1, 0–2 copies of 2 and 0–2 copies of 3: 2 × 3 × 3 = 18 (including the empty set). Without the skip the code would list all 2⁵ = 32 index subsets.
More Coding Interview Problems questions
- Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space. python def…
- Building a binary heap from n given keys: what are the worst-case costs of (i) bottom-up heapify and (ii) n successive inserts into an…
- In Java 8+, many keys that are Comparable and all land in ONE HashMap bucket. What is the worst-case cost of get() on that bucket once it…
- Problem: For each day, how many days until a strictly warmer day (0 if none)? python def wait(t): res, st = [0] len(t), [] for i, x in…
- Problem: The span of a stock on a day is the number of consecutive days up to and including it with price ≤ that day's price. python def…
- Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, the smaller explodes; equal sizes…