Data Structures & AlgorithmsModerateTCS NQT · tree warm-up
Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has depth 0. Run the code.
Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has depth 0. Run the code.
ch = {0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []}
cur = [0]
for _ in range(2):
cur = [v for u in cur for v in ch[u]]
print(len(cur))What is printed?- A. 3
- B. 2
- C. 4
- D. 5
Correct answer: A. 3
The depth-2 nodes are the children of 1 and 2, namely 3, 4 and 5, so the answer is 3. Counting the root's children (2) is the trap.
More Coding Interview Problems questions
- Problem: How many integers from 1 to 1000 are divisible by 3 or by 5 but not by both?
- Problem: What is the product of the distinct prime factors of 360? Run the code. python n = 360 p, prod = 2, 1 while p p <= n: if n % p ==…
- Problem: What is the sum of all primes up to 50? Run the code. python print(sum(p for p in range(2, 51) if all(p % d for d in range(2…
- Problem: What is C(20, 10) mod 1000? Compute it with Pascal's triangle reduced mod 1000. Run the code. python n, k = 20, 10 C = [[0] (k +…
- Problem: How many distinct palindromes can be formed by rearranging the letters of 'aabb' (distinct strings, all letters used)? Run the…
- Problem: What is the minimum number of deletions to make the string 'abcca' a palindrome? Use the palindromic-subsequence DP and print…