Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level, counting gaps. 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 maximum width of a tree: the largest number of positions between the leftmost and rightmost non-null nodes of a level, counting gaps. 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))
def width(root):
lvl, best = [(root, 0)], 0
while lvl:
best = max(best, lvl[-1][1] - lvl[0][1] + 1)
nxt = []
for n, i in lvl:
if n.l: nxt.append((n.l, 2 * i))
if n.r: nxt.append((n.r, 2 * i + 1))
lvl = nxt
return best
print(width(build([1, 3, 2, 5, None, None, 9, 6, None, None, None, None, None, 7])))What is printed?- A. 4
- B. 8
- C. 7
- D. 2
Correct answer: C. 7
Number positions like a heap (children 2i and 2i + 1) and take last − first + 1 on each level. On the deepest level, 6 (left child of 5) is at position 0 and 7 (left child of 9) is at position 6 → width 7 even though only two nodes exist. Counting nodes per level gives 2. O(n). In C++/Java, re-base indices per level to avoid overflow on deep trees.
More Coding Interview Problems questions
- Problem: Flatten a tree into a 'linked list' in preorder using right pointers, then print the values along the right pointers. Trees are…
- Problem: A trie stores n words of average length L over a 26-letter alphabet. Autocomplete must list whether any word starts with a prefix…
- Problem: Insert words into a trie and count how many stored words start with a given prefix. python def make(words): root = {} for w in…
- Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid. python def islands(g): R, C = len(g)…
- Problem: In a grid of fresh (1) and rotten (2) oranges, every minute rot spreads to 4-neighbours. Return the minutes until no fresh orange…
- Problem: Courses with prerequisites [a, b] (b before a). Return one valid order using Kahn's algorithm with a min-heap for ties, or [] if…