call(back)
Algorithms & Data Structuresmedium

Mark and Compact a Heap-Indexed Subtree

A memory manager stores a binary tree in an array: the node at index i has children at 2i+1 and 2i+2; a null slot means no node (and thus no subtree below it). Implement the GC operation markAndCompact(heapArray, k):

Mark the entire subtree rooted at index k as garbage, then compact the surviving values to the front of a new array, preserving their original order, and return [newArray, remap] where remap maps old index to new index for every survivor (references into the array must be patched — that is the remap's job). An out-of-range k, or a k pointing at a null slot, marks nothing — but compaction still drops the null slots.

markAndCompact(["A","B","C","D","E","F","G"], 1)
  -> [["A","C","F","G"], {0: 0, 2: 1, 5: 2, 6: 3}]

Asked at