Dense-Index Data Structure Code Review
Data Structure DesignModel answerLast 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:
- The structural invariants required for correctness
- How each operation achieves constant time complexity
- Critical bugs and edge cases to check for
- Code quality improvements you would recommend
Design Requirements
- Keys must remain exactly
0, 1, 2, ..., n-1wherenis 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Core Invariant
The fundamental invariant is index density: at all times between operations, if the collection contains n workers, they must occupy exactly keys 0 through n-1 with no gaps. This enables O(1) random selection by generating a random integer in [0, n) and directly accessing that key.
Operation Design and Complexity
Insert Operation
- Append the new worker at index
n(wherenis current size) - Increment size counter
- Time: O(1) - direct map insertion
Random Selection and Removal
- Generate random index
iin range[0, n) - Retrieve worker at index
i - If
i < n-1: move worker from indexn-1to indexi - Remove entry at index
n-1 - Decrement size counter
- Time: O(1) - constant number of map operations
The swap-with-last strategy preserves density by filling gaps with the rightmost element, avoiding the O(n) cost of shifting all subsequent entries.
Critical Edge Cases and Bugs
Empty Collection
- Selecting from empty map (size = 0) must be handled explicitly
- Generating random index in range
[0, 0)is undefined - Should either return null/error or throw an appropriate exception
- Must not decrement size below zero
Self-Swap Scenario
- When randomly selecting the last element (index
n-1), the swap operation would move this element to itself - This is logically valid but wasteful
- Implementation must either skip the swap when
i == n-1or handle the no-op correctly - Still must remove the entry and decrement size
Size Bookkeeping
- Size must be updated atomically with structural changes
- Decrementing before removal can expose an inconsistent state where size is
n-1butnentries exist - Correct order: perform removal operations, then update size as final step
- Or use size as the source of truth and ensure all key operations reference it consistently
Duplicate Handling
- Policy must be explicit: are duplicate worker IDs allowed?
- If not, insertion must check for existence first (making insert O(n) or requiring an auxiliary set)
- If yes, document that multiple entries for the same identity can exist
Concurrency Concerns
Atomicity of Select-and-Remove
- If selection and removal aren't atomic, concurrent calls can select the same worker twice
- Race condition: two threads both select index 3, both remove it, one succeeds while the other corrupts the structure
- Solution: either lock the entire operation or use atomic compare-and-swap patterns
- Consider whether partial operations leave the structure in a valid state
Visibility of Size Updates
- Size variable must be properly synchronized or marked volatile
- Without synchronization, threads may see stale size values leading to out-of-bounds access
Code Quality Improvements
Method Contracts and Documentation
- Document the empty-collection behavior explicitly
- Specify thread-safety guarantees (or lack thereof)
- State whether duplicate identities are permitted
- Document complexity guarantees in method comments
Naming and Clarity
- "adjust_map" is vague; prefer "compactIndices" or "fillGap"
- Consider separating concerns: "selectRandom" + "remove" rather than combined "pick"
- Use descriptive variable names: "lastIndex" not "last", "selectedIndex" not "i"
Error Handling
- Return
Optional<Worker>or similar for empty-case rather than null - Throw descriptive exceptions like
EmptyCollectionExceptionrather than generic errors - Validate preconditions with clear assertion messages
Testing Strategy
- Unit test: insert then remove single item, verify empty state
- Edge test: repeatedly remove until empty, verify boundary behavior
- Self-swap test: force selection of last element, verify correctness
- Statistical test: verify uniform distribution over thousands of selections (chi-squared test)
- Concurrency test: stress test with multiple threads if thread-safety claimed
Separation of Concerns
- Random number generation should be injectable for testing
- External recording service calls should be separated from structural operations
- Consider an explicit
size()query method rather than exposing internal counter
Complexity Verification
The design achieves O(1) operations specifically because:
- Map access by integer key is O(1)
- Swap requires exactly two map operations regardless of collection size
- Random index generation is O(1)
- No iteration through entries occurs
Any implementation that violates density by allowing gaps would require O(n) search to find valid entries, breaking the complexity guarantee.
Common Mistakes to Flag
- Forgetting to handle the self-swap case leads to unnecessary work but not incorrectness
- Removing before swapping leaves the last element inaccessible
- Generating random index in range
[0, n]instead of[0, n)causes out-of-bounds access - Not validating empty state before generating random index
- Inconsistent size updates causing transient invalid states
A strong code review would verify the dense-key invariant is maintained across all code paths, confirm O(1) complexity through careful operation counting, and ensure edge cases have explicit handling with appropriate tests.