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?
  1. A. 3 0 -1
  2. B. 3 2 1
  3. C. 2 2 -1
  4. 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

Exams that ask this topic