Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Vertical order traversal: group nodes by column (left child c − 1, right child c + 1); inside a column sort by row, then by value.

Problem: Vertical order traversal: group nodes by column (left child c − 1, right child c + 1); inside a column sort by row, then by value.
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
    nodes = [T(x) if x is not None else None for x in xs]
    kids = iter(nodes[1:])
    for nd in nodes:
        if nd:
            nd.l = next(kids, None); nd.r = next(kids, None)
    return nodes[0]
def vertical(root):
    cells = []
    def go(nd, r, c):
        if not nd: return
        cells.append((c, r, nd.v)); go(nd.l, r + 1, c - 1); go(nd.r, r + 1, c + 1)
    go(root, 0, 0); cells.sort()
    out = {}
    for c, r, v in cells: out.setdefault(c, []).append(v)
    return list(out.values())
print(vertical(build([3, 1, 4, 0, 2, 2])))
What is printed?
  1. A. [[0], [1], [3, 2], [4]]
  2. B. [[0], [1], [2, 3, 2], [4]]
  3. C. [[0], [1], [3, 2, 2], [4]]
  4. D. [[0], [1], [2, 2, 3], [4]]

Correct answer: C. [[0], [1], [3, 2, 2], [4]]

1's right child 2 and 4's left child 2 both sit at row 2, column 0, under the root 3 at row 0, column 0. Column 0 is therefore [3, 2, 2] (row first, then value), and duplicates are kept, not merged.

More Coding Interview Problems questions

Exams that ask this topic