Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once).
Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once).
def combo(k, s, n=9):
out = []
def bt(start, cur, rem):
if len(cur) == k:
if rem == 0: out.append(cur[:])
return
for x in range(start, n + 1):
if x > rem: break
cur.append(x); bt(x + 1, cur, rem - x); cur.pop()
bt(1, [], s)
return out
print(combo(3, 9))What is printed?- A. [[1, 2, 6], [1, 3, 5], [2, 3, 4], [3, 3, 3]]
- B. [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
- C. [[1, 2, 6], [1, 3, 5]]
- D. [[1, 3, 5], [2, 3, 4]]
Correct answer: B. [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
Choosing increasing numbers (start = x + 1) prevents reuse and duplicate orderings, and 'break' prunes once x exceeds the remainder. Sets of 3 distinct digits summing to 9: {1,2,6}, {1,3,5}, {2,3,4}. [3,3,3] repeats a number.
More Coding Interview Problems questions
- Problem: The recursive function below counts calls. How many times is f called for f(5)? python calls = 0 def f(n): global calls calls +=…
- Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications. python mults = 0 def power(x, n): global mults…
- Problem: Generate the letter combinations a phone keypad number can represent and report how many there are. python from itertools import…
- Problem: Count set bits for each number 0..n using DP on the lowest bit. python def bits(n): r = [0] (n + 1) for i in range(1, n + 1)…
- Problem: Check whether a number is a power of two and isolate its lowest set bit. python print("; ".join(f"{x > 0 and x & (x - 1) == 0} {x…
- Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space. python def single(a): ones = twos…