Build a List with a Tracking Cursor
Data Structure DesignModel answerLast 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Behavioral Contract
The implementation requires precise semantics defined upfront:
Position conventions: Use zero-indexed positions. A contiguous group is specified by (position, count) covering indices [position, position + count).
Cursor attachment: The cursor is bound to a specific item, not to a fixed index. When items are inserted before the tracked item, the cursor's numeric position increases to keep pointing at the same item—mirroring how text editor cursors behave.
Insertion rule: Inserting at the cursor's current position places new items before the tracked item, pushing it rightward.
Relocation semantics: Moving a group takes (source_pos, count, target_pos) where target_pos refers to the sequence after the group has been lifted out. Valid targets range from 0 to n - count. This eliminates ambiguity when source and destination overlap.
Deletion policy: When the tracked item is deleted, move the cursor to the item now occupying the first deleted position (the element immediately after the removed block). If deletion extends to the end, track the new final item. If the collection empties, the cursor becomes unset (None).
Empty state: An empty collection has no cursor.
API Design
insert(position, items) # Add items at given position
remove(position, count) # Delete count items starting at position
relocate(src_pos, count, dst_pos) # Move block to new location
set_cursor(position) # Point cursor at position
cursor_position() -> int | None # Get cursor index
cursor_item() -> item # Get tracked item
Invalid arguments raise exceptions. Zero-count operations are no-ops.
Cursor Update Logic
Let c denote the cursor's current index.
For insert(pos, k items):
- If
pos <= c: new cursor =c + k(tracked item shifted right) - If
pos > c: cursor unchanged
For remove(pos, L items):
- If
pos > c: cursor unchanged - If
pos + L <= c: new cursor =c - L(tracked item shifted left) - If cursor inside deleted range: apply deletion policy (move to
pos, clamped to valid range)
For relocate(src, L, dst):
First apply removal from src, then insertion at dst. If the cursor is inside the moved block, it maintains its relative offset within that block and ends up at dst + offset.
Correctness Reasoning
Every edit performs splicing: removing items at one location and/or inserting at another. An item's index changes only when a splice occurs before it:
- Items before the splice point retain their index
- Items after shift by the splice size
The cursor maintains "which item" rather than "which index," so it follows these same shift rules. The only special case is deletion of the tracked item itself, handled by the explicit deletion policy.
Implementation Approaches
Dynamic array with integer cursor
- Pros: Simple, excellent cache locality, O(1) cursor arithmetic
- Cons: Splicing costs O(n) due to element shifting
- Best for: Moderate-sized collections (up to ~100k items) or infrequent edits
- Cursor updates: O(1) arithmetic after splice completes
Doubly-linked list with node-reference cursor
- Pros: O(1) splicing once endpoints are located, cursor follows its node automatically
- Cons: O(n) to find positions by index, poor cache behavior
- Best for: Scenarios where code already holds node references
- Cursor updates: Free during moves, requires range check during deletion
Self-balancing tree with implicit indexing
- Pros: O(log n) operations via split/merge, scales to millions of items
- Implementation: Each node stores subtree size; compute positions by tree traversal
- Cons: Complex implementation, constant-factor overhead
- Best for: Large collections with frequent block operations
- Cursor updates: O(log n) to find current index after edits
Gap buffer
- Pros: O(1) amortized edits near a localized "hot spot"
- Cons: O(n) when edits jump around, poor for general block moves
- Best for: Text editors with sequential editing, not this general problem
Recommendation: Start with the array approach for clarity and typical performance. Switch to a balanced tree only if profiling shows the workload has large n and frequent moves.
Complexity (Array Implementation)
| Operation | Time | Extra Space |
|---|---|---|
| insert | O(n + k) | O(k) |
| remove | O(n) | O(1) |
| relocate | O(n) | O(count) |
| set_cursor, cursor_position, cursor_item | O(1) | O(1) |
Edge Cases to Handle
- Inserting at position 0 when cursor is at 0: cursor moves to k
- Inserting at end (position n): cursor unaffected
- Removing the single tracked item: cursor moves to former successor or becomes None
- Removing everything: cursor becomes None
- Relocating with
dst == src: no-op - Relocating a block containing the cursor: cursor relocates with its block
- Zero-length operations: valid no-ops
- Out-of-range arguments: raise IndexError
Python Implementation
from typing import Any, Iterable, List, Optional
class CursorList:
def __init__(self, items: Iterable[Any] = (), cursor: Optional[int] = None):
self._items: List[Any] = list(items)
self._cursor: Optional[int] = None
if cursor is not None:
self.set_cursor(cursor)
def __len__(self) -> int:
return len(self._items)
def __getitem__(self, index: int) -> Any:
return self._items[index]
def set_cursor(self, position: int) -> None:
if not 0 <= position < len(self._items):
raise IndexError(f"position {position} out of range")
self._cursor = position
def cursor_position(self) -> Optional[int]:
return self._cursor
def cursor_item(self) -> Any:
if self._cursor is None:
raise LookupError("cursor not set")
return self._items[self._cursor]
def insert(self, position: int, items: Iterable[Any]) -> None:
if not 0 <= position <= len(self._items):
raise IndexError(f"position {position} out of range")
block = list(items)
if not block:
return
self._items[position:position] = block
# Update cursor: items inserted before cursor push it right
if self._cursor is not None and position <= self._cursor:
self._cursor += len(block)
def remove(self, position: int, count: int) -> None:
if count < 0:
raise ValueError("count must be non-negative")
if not 0 <= position <= len(self._items):
raise IndexError(f"position {position} out of range")
if position + count > len(self._items):
raise IndexError(f"block extends beyond end")
if count == 0:
return
del self._items[position:position + count]
# Update cursor
if self._cursor is not None:
if position > self._cursor:
# Deletion after cursor: no change
pass
elif position + count <= self._cursor:
# Deletion entirely before cursor: shift left
self._cursor -= count
else:
# Cursor was in deleted range: apply policy
if len(self._items) == 0:
self._cursor = None
else:
self._cursor = min(position, len(self._items) - 1)
def relocate(self, src_pos: int, count: int, dst_pos: int) -> None:
if count < 0:
raise ValueError("count must be non-negative")
if not 0 <= src_pos <= len(self._items):
raise IndexError(f"source position {src_pos} out of range")
if src_pos + count > len(self._items):
raise IndexError(f"source block extends beyond end")
if not 0 <= dst_pos <= len(self._items) - count:
raise IndexError(f"destination position {dst_pos} out of range")
if count == 0 or src_pos == dst_pos:
return
# Extract block
block = self._items[src_pos:src_pos + count]
# Track if cursor is in the moved block
cursor_in_block = (self._cursor is not None and
src_pos <= self._cursor < src_pos + count)
cursor_offset = self._cursor - src_pos if cursor_in_block else None
# Remove from source
del self._items[src_pos:src_pos + count]
# Update cursor for removal
if self._cursor is not None and not cursor_in_block:
if src_pos < self._cursor:
self._cursor -= count
# Adjust dst_pos if source was before destination
if src_pos < dst_pos:
dst_pos -= count
# Insert at destination
self._items[dst_pos:dst_pos] = block
# Update cursor for insertion
if cursor_in_block:
self._cursor = dst_pos + cursor_offset
elif self._cursor is not None and dst_pos <= self._cursor:
self._cursor += count
Common Mistakes
- Forgetting that "insert at cursor position" should insert before the tracked item
- Using post-removal indices for destination in relocate, causing off-by-one errors
- Not handling the case where deletion empties the collection
- Implementing deletion policy inconsistently across operations
- Assuming the cursor tracks an index rather than an item
- Not validating that block operations stay within bounds