KatInterview

Dense-Index Data Structure Code Review

Data Structure DesignModel answer
MediumModel answerData Structure Designcode-reviewdata-structuresrandomization

Last updated

Review a structure storing items under contiguous integer keys with O(1) random selection and removal while preserving index density.

You're reviewing code for a service that manages a collection of workers. The implementation stores worker records in a map structure using consecutive integer keys beginning at 0. The system provides three operations:

  • Insert: Add a new worker to the collection
  • Random removal: Select a worker uniformly at random from all currently stored workers and remove them
  • Index repair: After removal, move the worker from the highest index into the gap left by the removed worker

Your task is to analyze this design as a code reviewer. Explain:

  1. The structural invariants required for correctness
  2. How each operation achieves constant time complexity
  3. Critical bugs and edge cases to check for
  4. Code quality improvements you would recommend

Design Requirements

  • Keys must remain exactly 0, 1, 2, ..., n-1 where n is the current number of workers
  • Random selection must be uniformly distributed across all stored workers
  • All operations must maintain O(1) expected or amortized time complexity
  • The repair operation cannot rebuild the entire structure by iterating through all entries

Points to Consider

  • How should the system behave when selecting from an empty collection?
  • Should duplicate worker identities be allowed or prevented?
  • If operations can happen concurrently, what atomicity guarantees are needed?
  • Where should the size counter be updated, and when should selected workers be recorded externally?

No implementation code is provided. Focus on describing what correct behavior looks like and what failure modes to watch for.

Hints

Hint 1

Consider what happens when you randomly select the worker at the highest index

Hint 2

Think about the order of operations: when do you decrement the count versus when do you perform the swap?

Hint 3

What assumptions does uniform random selection make about the key space?