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?- A. [[0], [1], [3, 2], [4]]
- B. [[0], [1], [2, 3, 2], [4]]
- C. [[0], [1], [3, 2, 2], [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
- Problem: Zigzag level-order traversal (left to right, then right to left, alternating). python class T: def init(s, v): s.v, s.l, s.r = v…
- Find the bug: this BST validator compares each node only with its own children. python class T: def init(s, v): s.v, s.l, s.r = v, None…
- A binary tree with 12 nodes is serialised in preorder, writing '#' for every missing child. How many '#' markers appear?
- Problem: Return the diameter of a binary tree (number of EDGES on the longest path between any two nodes). python class T: def init(s, v)…
- Problem: A node of a directed graph is 'safe' if every path from it ends at a terminal node (no outgoing edges). List the safe nodes…
- Problem: Find the bridges and articulation points of an undirected graph using DFS discovery times and low-links. python import sys…