Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target.
Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target.
def combos(c, t):
c.sort(); res = 0
def go(start, rem):
nonlocal res
if rem == 0: res += 1; return
for i in range(start, len(c)):
if i > start and c[i] == c[i-1]: continue
if c[i] > rem: break
go(i + 1, rem - c[i])
go(0, t)
return res
print(combos([2, 5, 2, 1, 2, 3], 5))What is printed?- A. 3
- B. 6
- C. 5
- D. 4
Correct answer: A. 3
Sorted: 1, 2, 2, 2, 3, 5. Distinct combinations: [1, 2, 2], [2, 3], [5]. Skipping equal siblings stops [1, 2, 2] from appearing 3 times (there are three 2s); without the skip the count would be larger.
More Coding Interview Problems questions
- Problem: Divide two integers without , / or %, truncating toward zero, using doubling (shifts). python def divide(a, b): neg = (a < 0) !=…
- Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first). python def diag(m): R, C = len(m), len(m[0]); out…
- Edge case: building a 3 × 3 grid with list multiplication. python grid = [[0] 3] 3 grid[0][0] = 1 print(grid) What is printed?
- Edge case: lambdas created in a loop (closures). python fs = [lambda: i 10 for i in range(3)] gs = [lambda i=i: i 10 for i in range(3)]…
- Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer. javascript const out = []; out.push("A")…
- Problem: Split an array (duplicates allowed) into the most chunks such that sorting each chunk separately and concatenating gives the…