Collections and Complexity

Picking a collection is a design decision with a complexity consequence attached, and in an LLD round it is graded as one. Nobody is asking you to write a hash table in 60 minutes. They are asking why you reached for a LinkedHashMap instead of a HashMap, what that costs, and what happens when the requirement changes. The deliverable is a defensible mapping from requirement to structure.

Why this matters: a wrong structure is one of the few LLD mistakes that makes a correctness claim false rather than the code merely ugly. Say “get is O(1)” with an ArrayList scan inside it and the sentence is wrong, not debatable. Interviewers probe this deliberately, because one follow-up separates the candidate who reached for ArrayList by reflex from the one who named the access pattern first: “what is the complexity of that?”


Prerequisites

  • Class Design Approach – structures get chosen after the entities and access patterns are written down, not before
  • Immutability and Equality – every hash-based structure here assumes a key whose hash code does not move
  • Concurrency – the concurrent collections below assume you know what a race is

The Problem: the O(n) scan hiding inside a reasonable-looking class

An LRU cache: a HashMap for the values, so lookups are O(1), and an ArrayList to remember which key was touched most recently. It passes its tests and reviews cleanly:

// A reasonable-looking LRU cache. The javadoc claims O(1). It is not.
public class LruCache<K, V> {
    private final int capacity;
    private final Map<K, V> values = new HashMap<>();
    private final List<K> order = new ArrayList<>();          // oldest first
    private final Map<K, Long> lastAccess = new HashMap<>();  // "for eviction"
    private long clock = 0;

    public LruCache(int capacity) { this.capacity = capacity; }

    /** O(1), backed by a HashMap. Allegedly. */
    public V get(K key) {
        V value = values.get(key);
        if (value == null) return null;
        order.remove(key);     // <-- indexOf scan, then arraycopy. O(n).
        order.add(key);        // now most recently used
        lastAccess.put(key, ++clock);
        return value;
    }

    public void put(K key, V value) {
        if (!values.containsKey(key) && values.size() == capacity) evictLru();
        values.put(key, value);
        order.remove(key);     // <-- same O(n), on every write
        order.add(key);
        lastAccess.put(key, ++clock);
    }

    private void evictLru() {
        K victim = null;
        long oldest = Long.MAX_VALUE;
        for (Map.Entry<K, Long> e : lastAccess.entrySet()) {   // <-- O(n) per eviction
            if (e.getValue() < oldest) { oldest = e.getValue(); victim = e.getKey(); }
        }
        values.remove(victim);
        lastAccess.remove(victim);
        order.remove(victim);  // <-- a third O(n), same call
    }
}

Three things are wrong, and the first is a mechanism you must be able to state out loud:

  1. ArrayList.remove(Object) is a linear scan, so the O(1) get is O(n). It calls indexOf, which walks the array calling equals until something matches, then System.arraycopy shifts every later element down a slot – two passes over up to n elements, in the hottest method the class has. And on a List<Integer>, order.remove(key) removes by value while order.remove(42) binds to remove(int index) and deletes the 43rd element.
  2. Eviction finds the minimum by iterating the whole map. The loop over lastAccess.entrySet() is O(n), and a cache at capacity evicts on nearly every put. “Always take the smallest” is a named access pattern with a structure attached – a heap, or a list already in order – and a linear min-scan over a hash map is the most common O(n) in machine-coding work.
  3. It degrades with size, so every test passes. A test with capacity 3 cannot tell O(1) from O(n); at 50,000 entries each get costs up to 50,000 equals calls, and the bug report reads “the cache got slower as it warmed up”. Three structures also track two facts here – order and lastAccess both encode recency – so one missed remove leaks a key forever. And the right structure shipped with the JDK: LinkedHashMap in access order, or a HashMap plus a doubly-linked list.

The decision table

Read it from the left column. The rows are access patterns, not class names, because the skill tested is turning a requirement into a structure.

What the requirement asks for Reach for Cost Watch for
Look up by key, or test membership HashMap / HashSet / unordered_map O(1) average; O(log n) worst case in Java 8+ Keys must be immutable
Look up by key and keep insertion or access order LinkedHashMap / OrderedDict O(1) average, plus two pointer writes Access order makes get a structural change
Always take the smallest or largest PriorityQueue / heapq / priority_queue O(log n) insert and poll, O(1) peek No arbitrary remove, no decrease-key
Ordered range scan – “bookings between 9 and 11” TreeMap / std::map O(log n) seek, then O(k) for k hits compareTo must agree with equals
Append and read by position ArrayList / list / vector O(1) amortised append, O(1) index, O(n) middle insert contains and remove(Object) are O(n)
Push and pop at either end – a queue or a stack ArrayDeque / deque / std::deque O(1) amortised at both ends Not Stack, not LinkedList
Hand work between threads, FIFO BlockingQueue / queue.Queue O(1) put and take, blocking when full or empty Bounded or not is a backpressure call
Membership on a huge set, false positives tolerable Bloom filter O(k) per probe for k hash functions No deletes; sized up front
Prefix lookup – autocomplete Trie O(L) in the key length, whatever the key count Node overhead per character

💡 Amortised O(1) = O(1) averaged over a run of operations, even though one in n of them is O(n). An ArrayList append is a single array write until the array fills – and that one append copies everything.

The non-obvious entry is the one no single row provides: a doubly-linked list removes in O(1) only when you already hold the node, and finding the node is the O(n) part. That is why every correct LRU pairs a map, to find the node, with a list, to move it.


Real-World Example: an LRU Cache, done twice

The first version is configuration on a library class; the second is what interviewers ask for when they want to watch you move pointers. Know both, and which is being asked for.

import java.util.*;

/**
 * Version 1: the whole LRU policy, in one constructor argument and one
 * override. Knowing this class exists is itself the interview signal.
 */
public class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    public LruCache(int capacity) {
        // accessOrder = true: get() moves the entry to the end of the list.
        // Default false gives insertion order, which is FIFO eviction, not LRU.
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    // Called after every insertion. Return true and LinkedHashMap drops the
    // head of its internal list -- the least recently used entry.
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}
// Caveat to say out loud: with accessOrder = true, get() mutates the list, so
// it throws ConcurrentModificationException during iteration and two threads
// calling get() corrupt it. Composition beats extends here.

/**
 * Version 2: HashMap for lookup, doubly-linked list for order. The map finds
 * the node in O(1), the list moves it in O(1); neither can do both.
 */
public class ManualLruCache<K, V> {

    private static final class Node<K, V> {
        final K key;                   // needed to evict from the map
        V value;
        Node<K, V> prev, next;
        Node(K key, V value) { this.key = key; this.value = value; }
    }

    private final int capacity;
    private final Map<K, Node<K, V>> index = new HashMap<>();
    private final Node<K, V> head = new Node<>(null, null);  // most recent side
    private final Node<K, V> tail = new Node<>(null, null);  // least recent side

    public ManualLruCache(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity <= 0");
        this.capacity = capacity;
        head.next = tail;    // two sentinels, permanently present, so every real
        tail.prev = head;    // node has a non-null prev and next
    }

    public V get(K key) {
        Node<K, V> node = index.get(key);
        if (node == null) return null;
        moveToFront(node);   // O(1): we were handed the node, not an index
        return node.value;
    }

    public void put(K key, V value) {
        Node<K, V> existing = index.get(key);
        if (existing != null) {
            existing.value = value;
            moveToFront(existing);
            return;
        }
        if (index.size() == capacity) evict();
        Node<K, V> node = new Node<>(key, value);
        index.put(key, node);
        linkAfterHead(node);
    }

    private void evict() {
        Node<K, V> lru = tail.prev;   // never the sentinel: size >= 1 here
        unlink(lru);
        index.remove(lru.key);        // forget this line and the map leaks
    }

    private void moveToFront(Node<K, V> node) { unlink(node); linkAfterHead(node); }

    // No null checks below. That is what the sentinels bought.
    private void unlink(Node<K, V> node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void linkAfterHead(Node<K, V> node) {
        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }
}
from collections import OrderedDict
from functools import lru_cache


class LruCache:
    """OrderedDict is a dict plus a doubly-linked list of keys -- Java's
    LinkedHashMap shape, with the relink exposed as move_to_end. A plain dict
    has been insertion-ordered since 3.7 but cannot be re-ordered."""

    def __init__(self, capacity: int) -> None:
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self._capacity = capacity
        self._entries: OrderedDict[str, object] = OrderedDict()

    def get(self, key: str) -> object | None:
        if key not in self._entries:
            return None
        self._entries.move_to_end(key)          # O(1) relink, newest at the end
        return self._entries[key]

    def put(self, key: str, value: object) -> None:
        if key in self._entries:
            self._entries.move_to_end(key)
        self._entries[key] = value
        if len(self._entries) > self._capacity:
            self._entries.popitem(last=False)   # last=False pops the OLDEST


# Batteries included: the same policy, with hit and miss counters for free.
# functools.cache is lru_cache(maxsize=None).
@lru_cache(maxsize=1024)
def price_for(sku: str, region: str) -> int:
    return _price_service.lookup(sku, region)   # only runs on a miss

price_for.cache_info()    # CacheInfo(hits=..., misses=..., maxsize=1024, ...)

# Caveats: arguments must be hashable, strong references pin memory for the
# process lifetime, and the cache is per-process.
#include <cstddef>
#include <list>
#include <optional>
#include <unordered_map>
#include <utility>

template <typename K, typename V>
class LruCache {
public:
    explicit LruCache(std::size_t capacity) : capacity_(capacity) {}

    std::optional<V> get(const K& key) {
        auto it = index_.find(key);
        if (it == index_.end()) return std::nullopt;
        // splice moves a node within the same list in O(1) and -- the detail
        // that matters -- does NOT invalidate iterators, so the one parked in
        // index_ stays valid and the map needs no update on a hit.
        entries_.splice(entries_.begin(), entries_, it->second);
        return it->second->second;
    }

    void put(const K& key, V value) {
        auto it = index_.find(key);
        if (it != index_.end()) {
            it->second->second = std::move(value);
            entries_.splice(entries_.begin(), entries_, it->second);
            return;
        }
        if (index_.size() == capacity_) {
            index_.erase(entries_.back().first);   // map entry, then the node
            entries_.pop_back();
        }
        entries_.emplace_front(key, std::move(value));
        index_.emplace(key, entries_.begin());
    }

private:
    using Entry = std::pair<K, V>;

    std::size_t capacity_;
    std::list<Entry> entries_;   // most recently used at the front
    std::unordered_map<K, typename std::list<Entry>::iterator> index_;
};

// Why std::list and not std::vector: a vector invalidates every iterator when
// it reallocates, so a map of iterators into one turns to garbage on the first
// growth. The price is an allocation per node.

Complexity honesty

When an interviewer asks for the complexity of your get, they want everything inside it accounted for, including the remove(Object) you did not write a loop for. “O(1) amortised, assuming the hash distributes reasonably” is a stronger answer than “O(1)” – not because it hedges more, but because it names the assumption, which is how you show you know where the bound came from. Say average for hash structures and give the worst case, say amortised where one operation in n does real work, and do not pretend constant factors away: O(n) over a contiguous ArrayList of 64 elements usually beats O(log n) through TreeMap nodes.


The five choices that come up in every machine-coding round

HashMap vs TreeMap vs LinkedHashMap

One question decides it: do you need ordering, and which kind? None means HashMap, O(1) average. Sorted by key means TreeMap, O(log n) for everything – and the reason to pick it is rarely the ordering itself but the navigation API: floorKey, ceilingEntry, subMap. Insertion or access order means LinkedHashMap, a HashMap threading a doubly-linked list through its entries for two extra pointer writes per insertion.

One detail earns credit beyond that: a HashMap bin in Java 8+ becomes a red-black tree past a threshold – eight nodes, in a table of at least 64 – so the collision worst case is O(log n), not the O(n) pre-8 answers still quote. For the key-side failure see Immutability and Equality: mutate a field the hashCode reads and the entry stays in the bin the old hash picked, unreachable by key forever.

ArrayList vs LinkedList

LinkedList is almost always wrong, and saying so with the reason beats reciting the O(1) insertion it advertises. That O(1) is conditional on already holding the node: add(i, x) and get(i) walk from an end first, so both are O(n), and only a pre-positioned ListIterator reaches the advertised bound. Memory finishes it – an allocation per node with two references of overhead, chased by pointer, against one contiguous array the prefetcher handles well. At LLD sizes, locality wins and the asymptotics never get a chance to matter.

For a queue or a stack, use ArrayDeque – not LinkedList, and not Stack, which extends Vector and synchronizes every method whether you asked or not. A linked list earns its place in one shape only: as an implementation detail reached through a map, as in the LRU above.

PriorityQueue and what it does not give you

A PriorityQueue is a binary heap: O(log n) insert, O(log n) poll of the extreme element, O(1) peek, and nothing else, because a heap only maintains that a parent is ordered against its children. Three things people expect are missing. Iteration is not sorted – it walks the backing array, which stuns everyone who prints one. Equal priorities are not FIFO, so add an increasing sequence number as a tiebreaker when arrival order matters. And there is no O(1) arbitrary removal and no decrease-key: remove(Object) scans the array for the element, so it is O(n).

That last omission is the most common LLD trap there is, because a scheduler usually has to cancel a queued task and a bare PriorityQueue cannot. Two standard answers. Lazy deletion: put the cancelled id in a set and let poll discard entries until a live one surfaces – O(1) to cancel, but dead entries stay resident, so memory grows with cancellations until you rebuild. An indexed heap: a Map<Id, Integer> from key to array position, updated inside every sift, buying O(log n) removal and decrease-key at the cost of owning the heap code. The second is what Task Scheduler needs the moment cancellation enters the requirements.

Concurrent collections

Collections.synchronizedMap takes one lock over the whole map per method, making individual calls safe, throughput single-threaded, and a sequence of calls still unsafe, since the lock drops between them. ConcurrentHashMap locks per bin and ships the compound operations as atomics. computeIfAbsent is the one to name: if (!map.containsKey(k)) map.put(k, new Session(k)); is two operations with a window between them, so two threads both pass the check and both create a session, while map.computeIfAbsent(k, Session::new) is one atomic operation per key. Two caveats – the mapping function must not touch the same map, and size() is approximate under concurrent writes because the count is striped across cells, so it is fine for a metric and wrong as a capacity check.

BlockingQueue is the producer-consumer primitive, with put and take absorbing the wait-and-notify you would otherwise hand-write. Bounded ArrayBlockingQueue versus unbounded LinkedBlockingQueue is a backpressure decision: bounded blocks the producer, unbounded turns the same overload into heap growth and an eventual OutOfMemoryError. And CopyOnWriteArrayList suits a listener registry – writes copy the array and cost O(n), reads iterate a frozen snapshot with no lock and no ConcurrentModificationException even when a listener unregisters itself mid-notification. Concurrency covers the primitives underneath.

When you need a structure the library does not have

Three actually come up. A trie for prefix search, when the requirement is autocomplete or “all SKUs starting with”: lookup is O(L) in the prefix length no matter how many keys exist, which a TreeMap cannot match once you want all completions rather than one key (Tries). An interval structure for overlap detection, where the honest answer is usually that you do not need one – keep bookings in a TreeMap from start to end time, and floorEntry(newStart) plus ceilingKey(newStart) answers “does this overlap anything” in two O(log n) probes, which is what Meeting Scheduler runs on. A real interval tree earns its keep only with heavily overlapping intervals. And a Bloom filter for a cheap negative answer on a huge set: a few hash probes say “definitely not present” with no false negatives, saving the lookup behind it (Bloom Filters).

The rule for all three: reach for a custom structure only when a measured access pattern has no library answer. A trie built because the problem mentions strings, in front of 200 product names, is over-engineering with extra steps.


When to Use the Library Structure vs When to Hand-Roll

Use the library structure when Hand-roll when
The access pattern maps onto a named structure The interviewer asks for the internals – “LRU without LinkedHashMap”
The ordering you need is insertion, access, or by key You need two orderings at once over the same entries, as LFU does
ConcurrentHashMap or a BlockingQueue covers thread safety The library omits the operation – O(log n) cancel, decrease-key
You want the choice reviewable in one glance The structure is what is being graded, like a rate limiter’s ring buffer
n is modest and O(log n) is nowhere near the bottleneck A measured profile blames the structure’s memory or constants

The characteristic failure mode is the structure chosen by habit rather than by access pattern, because the resulting linear scan does not look like a loop: list.contains(order), list.remove(key), list.indexOf(node) are one method call each, O(n) each, invisible in review. The audit is mechanical – for each public method, write the real cost beside every collection operation it performs. Anything O(n) on a hot path is either a HashMap you did not add or a sort you did not do once up front.


Interview Questions

  1. “LinkedList has O(1) insertion. Why is it rarely the right answer?” – Because the O(1) assumes you already hold the node, and the API mostly will not let you: get(i) and add(i, x) walk from an end first, so both are O(n). The constant factor finishes it: an allocation per node, chased by pointer, against one contiguous array the prefetcher likes. Use ArrayDeque for a queue or stack; a linked list belongs inside something else, reached through a map, as in an LRU.

  2. “How do you cancel an entry that is already in a PriorityQueue?” – Not in better than O(n) with a bare one, because remove(Object) scans the backing array before it can sift. Two real options: lazy deletion, where the cancelled id goes into a set and poll discards dead entries until a live one surfaces, which is O(1) to cancel but leaves cancelled work resident until you rebuild; or an indexed heap, keeping a map from key to array position updated inside every sift, which gives O(log n) removal and decrease-key at the cost of owning the heap code.

  3. “HashMap vs ConcurrentHashMap vs synchronizedMap, and what does computeIfAbsent buy you?” – HashMap is unsynchronized and concurrent writes corrupt it, historically badly enough to spin a thread forever during a resize. synchronizedMap locks the whole map per call, so throughput is one thread and compound sequences still race because the lock drops between calls. ConcurrentHashMap locks per bin and exposes compound operations as atomics: computeIfAbsent collapses check-then-act into one atomic per-key operation, so two threads racing to create a session produce one.

  4. “How would you keep a leaderboard of the top K scores updated?” – A min-heap capped at K: each incoming score compares against the root in O(1), only a winner costs an O(log K) replace, and memory is K rather than the number of players. What you give up is everything outside the window – no answer to “what rank am I”, and no way to handle a score revised downwards, because the displaced entries are gone. Keeping everyone in a TreeMap from score to players, or a skip list as Redis does, costs O(log n) per update and answers rank queries.

  5. “TreeMap range scan, or a sorted ArrayList with binary search?” – Mutation frequency decides it. Both find a boundary in O(log n), but the array wins on constant factor and memory, being contiguous with no per-entry node, and loses hard on insertion, where an element in the middle costs an O(n) System.arraycopy. So the sorted array is right when data is built once and read many times – a static fare table, an index rebuilt nightly – and TreeMap is right when writes and reads interleave, as in any booking or order-book problem.


See It in Action