Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Convert a sorted array into a height-balanced BST and print its preorder.
Problem: Convert a sorted array into a height-balanced BST and print its preorder.
def pre(a, lo, hi, out):
if lo > hi: return out
mid = (lo + hi) // 2
out.append(a[mid])
pre(a, lo, mid - 1, out)
pre(a, mid + 1, hi, out)
return out
print(pre([1, 2, 3, 4, 5, 6, 7], 0, 6, []), pre([1, 2, 3, 4], 0, 3, []))What is printed?- A. [4, 2, 1, 3, 6, 5, 7] [3, 2, 1, 4]
- B. [4, 2, 6, 1, 3, 5, 7] [2, 1, 3, 4]
- C. [4, 2, 1, 3, 6, 5, 7] [2, 1, 3, 4]
- D. [1, 2, 3, 4, 5, 6, 7] [2, 1, 3, 4]
Correct answer: C. [4, 2, 1, 3, 6, 5, 7] [2, 1, 3, 4]
Pick the middle as the root, recurse on both halves. With an even length, (lo + hi) // 2 picks the lower middle (2), so 3 and 4 form the right subtree. [4, 2, 6, 1, 3, 5, 7] is the level order, not the preorder. O(n).
More Coding Interview Problems questions
- Problem: A tree has n = 10⁵ nodes and arrives as a parent array. You must answer 10⁵ queries 'is u an ancestor of v?'. Which preprocessing…
- Problem: A tree of n nodes is stored as a skewed BST (keys inserted in increasing order). What is the cost of the recursive height…
- Problem: Check whether two trees are mirror images of each other (here: whether a tree is symmetric). Trees are built by build(xs): a…
- 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…
- 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…