Skip to content

Find Dead Heap Objects

Published 3 October 2026

Coding Part 1 — Find Heap Objects Not Referenced by the Stack

The first version defined a simple heap object containing only a memory address.

class HeapObject:
    address: int

The function received:

dead_objects(
    stack_addresses,
    heap_objects
)

stack_addresses represented memory addresses directly referenced from the stack, while heap_objects represented objects currently allocated on the heap.

The task was to return the heap objects that were not reachable from any address on the stack.

For example, suppose the stack contains:

[120, 480]

and the heap contains objects located at:

120
275
480
630

Then the objects at addresses 275 and 630 would be considered dead in this simplified version because neither address appears among the stack references.

Coding Part 2 — Follow References Between Heap Objects

The interviewer then extended the object definition so that a heap object could hold references to other heap objects.

class HeapObject:
    address: int
    references: List[int]

The definition of reachability now became recursive: an object should remain alive not only when the stack points to it directly, but also when it can be reached indirectly through references from another live heap object.

For example:

Stack:
[120]

Heap:
120 -> [275]
275 -> [480]
480 -> []
630 -> []

In this case, objects 120, 275, and 480 are all reachable from the stack through the reference chain.

The object at address 630 is not reachable through any path and should therefore be returned as a dead object.