Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Convert a BST so each node's value becomes the sum of all values ≥ it (reverse inorder with a running sum); print the new inorder.
Problem: Convert a BST so each node's value becomes the sum of all values ≥ it (reverse inorder with a running sum); print the new inorder.
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def ins(r, v):
if not r: return T(v)
if v < r.v: r.l = ins(r.l, v)
else: r.r = ins(r.r, v)
return r
root = None
for v in [5, 2, 13, 1, 4, 9]: root = ins(root, v)
acc = 0
def conv(n):
global acc
if not n: return
conv(n.r); acc += n.v; n.v = acc; conv(n.l)
conv(root)
out = []
def ino(n):
if n: ino(n.l); out.append(n.v); ino(n.r)
ino(root); print(out)What is printed?- A. [1, 3, 7, 12, 21, 34]
- B. [34, 33, 31, 27, 22, 13]
- C. [34, 32, 28, 23, 22, 13]
- D. [33, 31, 27, 22, 13, 9]
Correct answer: B. [34, 33, 31, 27, 22, 13]
Sorted keys 1, 2, 4, 5, 9, 13 (total 34). Going from largest down: 13 → 13, 9 → 22, 5 → 27, 4 → 31, 2 → 33, 1 → 34, so the inorder is [34, 33, 31, 27, 22, 13].
More Coding Interview Problems questions
- Problem: Count subtrees in which every node has the same value. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border. python import…
- Problem: Remove the fewest DISTINCT values so that at least half of the array's elements are removed (greedy on frequencies). python from…
- Problem: Find a target's index in a rotated sorted array of distinct values in O(log n). python def search(a, t): lo, hi = 0, len(a) - 1…
- Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an…
- Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to…