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?- A. [4, 2, 12, 3, 7]
- B. [4, 2, 1, 3, 7]
- C. [4, 7, 12, 9, 7]
- 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
- Problem: Find the minimum depth (nodes on the shortest root-to-LEAF path). The candidate below is buggy. Trees are built by build(xs): a…
- Problem: Insert keys into an empty BST in the given order and report the preorder traversal. python def insert(t, k): if t is None: return…
- Problem: Delete key 50 (a node with two children) from the BST built by inserting 50, 30, 70, 60, 80, 65 – replacing it with its inorder…
- Problem: Given the root of a BST with n nodes and a target, return the value closest to the target. What is the best time complexity…
- Problem: Return the maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level…
- Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are…