Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital root).
Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital root).
def root(n): return 0 if n == 0 else 1 + (n - 1) % 9 print(root(38), root(999999999), root(0), root(10**18 + 7))What is printed?
- A. 2 0 0 8
- B. 11 9 0 8
- C. 2 9 1 8
- D. 2 9 0 8
Correct answer: D. 2 9 0 8
A number is congruent to its digit sum mod 9, so the repeated digit sum is 1 + (n − 1) mod 9 for n > 0. 38 → 11 → 2. A multiple of 9 gives 9, not 0 (n % 9 would wrongly give 0). 10¹⁸ + 7 → 1 + 7 = 8. O(1).
More Coding Interview Problems questions
- Problem: Count pairs (i < j) with a[i] > a[j] (inversions) in an array of n = 2 × 10⁵ values. Which approach runs within a 1-second limit?
- Problem: Answer q = 10⁵ queries 'sum of a[l..r]' on a static array of n = 10⁵ values. Which approach is best?
- Problem: An array of n = 10⁵ values receives 10⁵ operations, each either 'add v to a[i]' or 'sum of a[l..r]'. Which data structure gives…
- Problem: n ≤ 18 cities, find the shortest route visiting every city exactly once (travelling salesman). Which approach fits?
- Problem: n = 10⁵ intervals; for each, count how many other intervals it overlaps. What is the best complexity?
- Problem: A function does for i in range(n): for j in range(i, n, i + 1): work(). What is its time complexity?