KatInterview

Leaked Allocations: Filter Blocks Missing From Live Pointers

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashinghash-setfilteringorder-preservation

Last updated

Filter a list of allocated block addresses to those absent from a list of live pointers, keeping the original order, using hash-set membership for linear-time performance.

Orphaned Memory Blocks

A tiny runtime tracks memory in two pieces:

  • allocated: a list of integers, each the starting address of a block currently allocated on the heap.
  • live_pointers: a list of integers, each an address currently held by some variable in the call stack.

Blocks in this runtime never point at one another, so there is nothing to follow transitively. A block is in use exactly when its address appears in live_pointers. Every other block is orphaned.

Write a function that returns the addresses of all orphaned blocks.

Rules

  • Output addresses in the same relative order in which they appear in allocated.
  • Do not modify either input list.
  • live_pointers may contain repeated values, and may contain addresses that are not in allocated. These have no effect on the result.
  • If allocated itself contains the same address more than once, treat each occurrence independently: an orphaned address appears in the output once per occurrence, and an in-use address is removed in every occurrence. Do not deduplicate the output.
  • If nothing is in use, return a new list with the same contents as allocated. If everything is in use, return an empty list.

Constraints

  • 0 <= len(allocated) <= 10^5
  • 0 <= len(live_pointers) <= 10^5
  • 0 <= address <= 2^63 - 1
  • Aim for roughly linear time; comparing every block against every pointer is too slow at the upper limits.

Examples

Example 1

Input: find_orphaned_blocks([1000, 1008, 1016, 1024, 1032], [1008, 9999, 1008, 1032])

Output: [1000, 1016, 1024]

Example 2

Input: find_orphaned_blocks([16, 32], [])

Output: [16, 32]

Hints

Hint 1

Ask only one question about the pointers: is this address present? That suggests a structure with fast membership tests.

Hint 2

Build a set from live_pointers once. Repeated values collapse and unknown addresses are simply never looked up.

Hint 3

Walk through allocated from left to right and keep each address not in the set; this keeps the order and creates a new list rather than modifying the input.