Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: A warehouse aisle has shelves with weights; find the leftmost 'balance shelf' i such that the total weight strictly to its left equals the total strictly to its right (−1 if none).
Problem: A warehouse aisle has shelves with weights; find the leftmost 'balance shelf' i such that the total weight strictly to its left equals the total strictly to its right (−1 if none).
def balance(a):
total, left = sum(a), 0
for i, x in enumerate(a):
if left == total - left - x:
return i
left += x
return -1
print(balance([2, 3, -1, 8, 4]), balance([1, -1, 4]), balance([1, 2, 3]))What is printed?- A. 3 0 -1
- B. 3 2 1
- C. 2 2 -1
- D. 3 2 -1
Correct answer: D. 3 2 -1
With total T and left sum L before index i, the right sum is T − L − a[i]. [2, 3, −1, 8, 4]: T = 16; at i = 3, L = 4 and right = 16 − 4 − 8 = 4 → 3. [1, −1, 4]: T = 4; at i = 2, L = 0 and right = 4 − 0 − 4 = 0 → 2 (an empty side counts as 0). [1, 2, 3] has no such shelf. One pass, O(n), O(1) extra.
More Coding Interview Problems questions
- Problem: A street has n = 6 lamps, all starting at brightness 0. Each command (l, r, v) adds v to every lamp from l to r (0-based…
- Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one…
- 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: 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…