Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays.
Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays.
def all_subarray_sums(a):
n = len(a)
return sum(x * (i + 1) * (n - i) for i, x in enumerate(a))
def brute(a):
return sum(sum(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1))
print(all_subarray_sums([4, 1, 3]), brute([4, 1, 3]), all_subarray_sums([2, -1, 2, 5]))What is printed?- A. 25 25 30
- B. 25 8 34
- C. 25 25 34
- D. 8 25 34
Correct answer: C. 25 25 34
A subarray containing index i picks its start among i + 1 positions and its end among n − i positions. [4, 1, 3]: 4·(1·3) + 1·(2·2) + 3·(3·1) = 12 + 4 + 9 = 25, matching the brute force 4 + 1 + 3 + 5 + 4 + 8. [2, −1, 2, 5]: 2·4 − 1·6 + 2·6 + 5·4 = 8 − 6 + 12 + 20 = 34. The contribution trick is O(n); the brute force is O(n³) (O(n²) with running sums). Just summing the array (8) ignores how often each element is counted.
More Coding Interview Problems questions
- Problem: A login service flags an account if the same device ID appears twice within at most k positions of the access log (|i − j| ≤ k)…
- Problem: A DP table for a 2 × 3 grid is created in two ways and one cell is set in each. python dp = [[0] 3] 2 dp[0][1] = 5 dp2 = [[0] 3…
- Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts. python def oddsumsubarrays(a): even, odd, run, res…
- Problem: Find the length of the LONGEST contiguous subarray whose sum equals k; values can be negative, so a sliding window is not valid…
- Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window. python def…
- Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and…