Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the vertical sum of a tree for every column, left to right (root column 0, left child −1, right child +1). Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Return the vertical sum of a tree for every column, left to right (root column 0, left child −1, right child +1). Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
    def __init__(self, v, l=None, r=None):
        self.v, self.l, self.r = v, l, r
def build(xs, i=0):
    if i >= len(xs) or xs[i] is None: return None
    return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
from collections import defaultdict
def vertical(root):
    col = defaultdict(int)
    def go(t, c):
        if not t: return
        col[c] += t.v
        go(t.l, c - 1); go(t.r, c + 1)
    go(root, 0)
    return [col[c] for c in sorted(col)]
print(vertical(build([1, 2, 3, 4, 5, 6, 7])))
What is printed?
  1. A. [4, 2, 12, 3, 7]
  2. B. [4, 2, 1, 3, 7]
  3. C. [4, 7, 12, 9, 7]
  4. D. [4, 2, 6, 3, 7]

Correct answer: A. [4, 2, 12, 3, 7]

Columns: 4 at −2; 2 at −1; 1, 5, 6 at 0 (5 = left's right, 6 = right's left) → 12; 3 at +1; 7 at +2. O(n) plus sorting the columns.

More Coding Interview Problems questions

Exams that ask this topic