Based on your description, I recommend a singly linked list as the best data structure for your use case. I'll explain why below, including assumptions, how it fits your operations, alternatives, and when to choose something else. I'll also provide short code examples to illustrate.
Key Assumptions from Your Description
- Keys and objects: You have unique integer keys (within some interval/range, e.g., [low, high]) associated with objects. I assume the structure maintains them in sorted ascending order by key (to support "look up first few ascending keys").
- "Look up first few ascending keys": This means retrieving the objects associated with the smallest few keys (e.g., the first m, where m is small), in ascending key order. This is the most common operation.
- "Remove front": Remove the current smallest key (and its object).
- "Add front": Add a new key-object pair as the new smallest ("front"). This assumes the new key is always smaller than the current smallest—to keep the list sorted without expensive insertions. If this assumption is wrong (e.g., new keys could be larger), see alternatives below.
- "Deeper lookup in interval is rare": This means rarely needing to access/retrieve objects for larger ("deeper") keys in the sorted order or interval. I assume this could involve either:
- Traversing deep into the sorted order to get large keys (O(n) time is OK if rare).
- Looking up an object by a specific key (O(n) search time is OK if rare).
- No other operations: No frequent random lookups, no removes/adds in the middle or back, no updates to existing keys. n (number of items) could be large, but m (number of "first few" lookups) is small.
- Interval: The "interval" suggests keys are bounded integers (e.g., [1, 1000000]), but not necessarily dense or consecutive. If they are dense/consecutive, see alternatives below.
- Performance priorities: Frequent operations should be fast (O(1) or O(m)). Rare operations can be slower (O(n)).
If any assumption is wrong, see the alternatives section.
Why a Singly Linked List?
- It's simple, efficient for your operations, and optimized for frequent access/updates at the front (smallest keys).
- The list is maintained in sorted ascending order by key, with the head as the smallest key.
- No need for a complex balanced tree, since updates are only at the front and we assume added keys are always the new smallest.
- Space: O(n).
- If n is very large and "deeper lookup" means frequent random access by key (even if rare), you can augment it with a hash map (see below).
Operation Performance
- Look up first few ascending keys: Start at head and traverse m nodes. Time: O(m). Space: O(1) (or O(m) if copying results).
- Remove front: Remove the head node. Time: O(1).
- Add front: Create a new node and set it as the new head (assumes new key < current head's key). Time: O(1).
- Deeper lookup (rare):
- If it means "get the k-th smallest key/object" for large k: Traverse from head. Time: O(k) = O(n) in worst case (acceptable if rare).
- If it means "get object by specific key": Traverse from head and search. Time: O(n) in worst case (acceptable if rare).
- Other: Full traversal (e.g., to check size or dump all keys) is O(n), but not mentioned as needed.
This perfectly matches your "almost always" lookup of small m, with O(1) updates only at front. Deeper operations are linear-time but rare, so no issue.
Example Implementation
Here's a simple example in Python (easy to adapt to Java, C++, etc.). Each node holds a key and object.
class Node:
def __init__(self, key, obj):
self.key = key
self.obj = obj
self.next = None
class SortedLinkedList:
def __init__(self):
self.head = None
# Look up first m ascending keys (returns list of (key, obj) tuples)
def lookup_first_few(self, m):
result = []
current = self.head
while current and len(result) < m:
result.append((current.key, current.obj))
current = current.next
return result
# Remove front (smallest key)
def remove_front(self):
if self.head:
self.head = self.head.next
# Add front (assumes new_key < current head key if exists)
def add_front(self, new_key, new_obj):
new_node = Node(new_key, new_obj)
new_node.next = self.head
self.head = new_node
# Rare: Deeper lookup by key (returns obj or None)
def deeper_lookup_by_key(self, target_key):
current = self.head
while current:
if current.key == target_key:
return current.obj
current = current.next
return None
# Usage
sll = SortedLinkedList()
sll.add_front(1, "obj1") # Head: 1
sll.add_front(0, "obj0") # Head: 0 -> 1
print(sll.lookup_first_few(2)) # [(0, 'obj0'), (1, 'obj1')]
sll.remove_front() # Head: 1
sll.add_front(-1, "obj-1") # Head: -1 -> 1
print(sll.deeper_lookup_by_key(1)) # 'obj1' (traverses list, rare)
In Java, use a custom Node class and manage head similarly (or use LinkedList but customize for your ops).
Augmentation for Faster Deeper Lookup (If Needed)
If "deeper lookup" specifically means "get object by key" (not by position) and O(n) is too slow even for rare cases, add a hash map alongside the linked list:
- Hash map: key → object (or key → node if you need node access).
- On add_front: Update hash map in O(1).
- On remove_front: Remove from hash map in O(1).
- Deeper lookup by key: O(1) via hash map.
- Space: Extra O(n).
- This doesn't affect the linked list for ordered lookups.
Example in Python:
# Inside SortedLinkedList class
def __init__(self):
self.head = None
self.key_to_obj = {} # Hash map
def add_front(self, new_key, new_obj):
# ... same as above
self.key_to_obj[new_key] = new_obj
def remove_front(self):
if self.head:
del self.key_to_obj[self.head.key]
self.head = self.head.next
def deeper_lookup_by_key(self, target_key):
return self.key_to_obj.get(target_key, None)
This is essentially what LinkedHashMap provides in Java, but customized for sorted order and front-only updates.
Alternatives
If my assumptions don't hold, consider these:
- If added keys aren't always the new smallest (e.g., arbitrary keys): Use a balanced binary search tree (BST) like
TreeMap<Integer, Object> in Java, std::map in C++, or sortedcontainers.SortedDict in Python.
- Lookup first m: Iterate from start, O(log n + m).
- Remove front: O(log n).
- Add (anywhere): O(log n) — tree auto-sorts it.
- Deeper lookup by key: O(log n).
- Why? No assumption on added key; always sorted. Good if n > 10^5 and O(1) updates aren't critical.
- If keys are dense/consecutive in a small fixed interval (e.g., [1, 1000]): Use an array or vector of size (high - low + 1). Index by key - low.
- Lookup first m: Scan from start, O(m).
- Remove/add front: Shift elements, O(n) — bad if frequent.
- Better: Track current min_key pointer, increment on remove, decrement on add.
- Deeper lookup: O(1) by index.
- If you need the first m frequently but in arbitrary order: A min-heap (priority queue) like
PriorityQueue in Java.
- But getting first m requires extracting m times (O(m log n)), then re-inserting if not destructive. Not ideal for "lookup" without removal.
- If it's like a queue (FIFO, not strictly sorted by key): Use a deque (
ArrayDeque in Java, collections.deque in Python). O(1) add/remove front, O(m) to copy first m. But no inherent sorting—add sorting if needed.
- If n is huge and deeper lookup must be O(log n) always: Use an order-statistic tree (BST with rank support, like GNU Policy-Based Data Structures in C++) for O(log n) get-kth.
When to Choose Something Else
- If updates aren't strictly "front only" or the new key isn't always smallest: Go with TreeMap/BST.
- If you need frequent deeper lookups by key: Use TreeMap or linked list + hash map.
- If space is tight and keys are sparse in a large interval: BST is better (no wasted space like an array).
- Test with your real workload: If n < 10^4, even O(n) operations are fine; for larger n, prefer O(log n).
If this doesn't match your needs (e.g., clarify "deeper lookup," "interval," or if keys can be added non-smallest), provide more details for a better recommendation!