Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
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 level-order list where index i has children 2i+1 and 2i+2 (None = no node).
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 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 bad(t):
if not t: return 0
return 1 + min(bad(t.l), bad(t.r))
def good(t):
if not t: return 0
if not t.l: return 1 + good(t.r)
if not t.r: return 1 + good(t.l)
return 1 + min(good(t.l), good(t.r))
r = build([1, 2, None, 3, 4])
print(bad(r), good(r))What is printed?- A. 2 3
- B. 1 2
- C. 1 3
- D. 3 3
Correct answer: C. 1 3
The root has no right child, but an empty side is not a leaf. The buggy version takes min(…, 0) and reports depth 1. The correct version only uses a missing side when both are missing (a real leaf): root → 2 → 3 = 3. BFS that stops at the first leaf is also O(n) and often faster.
More Coding Interview Problems questions
- 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…
- 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…