KatInterview

Build a List with a Tracking Cursor

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structuresinvariantsapi-design

Last updated

Design a mutable list with a cursor that stays attached to its element as items are inserted, removed, or relocated within the collection.

You need to implement a collection that holds an ordered list of items along with a cursor that tracks one specific item in the collection.

Your implementation must support:

  • Inserting a group of items at any position
  • Removing a contiguous group of items
  • Relocating a contiguous group from one position to another
  • Positioning the cursor to point at a specific item
  • Querying the cursor's current position and the item it points to

Define clear behavior for your cursor:

  • What happens to the cursor when items are added before it, after it, or at its exact position?
  • How should the cursor behave when the item it tracks gets moved to a different position?
  • What should happen if the tracked item is deleted?

Propose an API, explain the cursor's behavioral rules, discuss implementation options with their performance characteristics, and provide working code for one approach.

Hints

Hint 1

The cursor should track the actual item, not just a numeric index that could become stale after edits.

Hint 2

Define your semantics precisely before coding: where does 'insert at position k' place items relative to the cursor if it's at position k?

Hint 3

Consider how remove and relocate can be expressed as combinations of simpler splice operations, which helps derive the cursor update logic systematically.