Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Fundamentals
26 min read

Java Data Structures: 10 Essentials — Principles, Source Code & Selection Guide

This article explains 10 essential Java data structures — arrays, linked lists, stacks, queues, hash maps, heaps, BSTs, B+ trees, skip lists, and graphs — covering their memory layout, time complexities, Java implementations, common pitfalls, and selection criteria for interviews and system design.

1. Global View: Decision Diagram & Comparison Table

1.1 Selection Decision Diagram

Data structures have no absolute superiority; only access pattern fit matters. When choosing, ask three questions: Is access random or sequential? Where are insertions/deletions concentrated? Is data in memory or on disk?

"Red-black trees govern in-memory ordering, B+ trees govern on-disk ordering, skip lists govern concurrent ordering." "Need fast lookup? Use array/hash. Need range queries? Use tree/skip list. Need to control entry/exit order? Use stack/queue/heap."

1.2 Panorama Comparison Table

Structure        Lookup           Insert/Delete   Ordering      Java / Middleware Implementation   One-line Memory Aid
Array            O(1) by index    O(n) shift      Unordered     ArrayList                            Physically contiguous, CPU cache's favorite
Linked List      O(n)             O(1)*           Can be ordered LinkedList, LRU chain                Weak alone, powerful combined
Stack            O(n)             O(1)            LIFO          ArrayDeque, JVM stack frames         Undo pill, monotonic stack crushes dimensions
Queue            O(n)             O(1)            FIFO          BlockingQueue, thread pools          Buffer belt, boundary is lifeline
Hash Table       Avg O(1), worst O(n) Avg O(1)      Unordered     HashMap / ConcurrentHashMap          Equality king, fears collisions and concurrency
Heap             Peek O(1)        O(log n)        Partial order PriorityQueue                        Only cares about top, TopK standard
BST              O(log n)~O(n)    O(log n)        In-order sorted TreeMap (red-black)                  Insurance for worst case
B+ Tree          O(logₘ n)        O(logₘ n)       Ordered       MySQL InnoDB index                   Short & fat, optimal for disk I/O
Graph            Traversal O(V+E) O(1) add edge   Topological   Adjacency list                       Everything is relationship, topology decides fate
Skip List        Avg O(log n)     O(log n)        Ordered       ConcurrentSkipListMap, Redis ZSet    Coin-flip for lock-free ordering
Linked list's O(1) has a precondition trap : must already hold node reference, otherwise locating is O(n). LinkedList.remove(i) remains O(n) overall — a frequent interview trap.

2. Four Linear Brothers: Array, Linked List, Stack, Queue

2.1 Array: Wins on Physical Contiguity, Not Just O(1)

Array essence is contiguous memory: addr = base + i * size, one multiply-add for direct addressing → random access O(1). Cost: middle insert/delete shifts O(n), resize allocates new array and copies whole block.

Index:  0   1   2   3   4
Memory: [10][20][30][40][50]  << contiguous, CPU cache friendly
Address = base + i * element_size  << single instruction computes

Key insights:

True winner is CPU cache locality, not complexity. CPU fetches a cache line (64B, ~16 ints); sequential traversal hits hardware prefetch every time. Linked list nodes scattered across heap → each hop a cache miss. For 10M elements, array often 3-5x faster. ArrayList grows by 1.5x ( oldCapacity + (oldCapacity >> 1)), initial capacity 10 is lazily allocated on first add . Multiplicative growth ensures amortized O(1); fixed-step growth degrades to O(n²) copying.

Middle insert uses System.arraycopy (underlying memmove, bulk block copy + SIMD), often faster than LinkedList finding position first.

2D array row-major traversal is multiples faster than column-major; multi-thread writes to adjacent variables on same cache line cause False Sharing , solved by LongAdder with @Contended padding.

// ArrayList grow core (JDK source simplified)
private Object[] grow(int minCapacity) {
    int oldCap = elementData.length;
    int newCap = oldCap + (oldCap >> 1);  // 1.5x growth
    return elementData = Arrays.copyOf(elementData, Math.max(newCap, minCapacity));
}

Two practical pitfalls:

Resize thrashing: Arrays.copyOf is O(n); many add triggering repeated copies cause CPU spikes. Known size → new ArrayList<>(expectedSize) pre-size; bulk data use addAll to expand once; extreme cases (e.g., Disruptor) use pre-allocated ring array, never move. Arrays.asList() returns fixed-size view; calling add throws UnsupportedOperationException.

Classic two-pointer array problem (LeetCode 26 in-place dedup, O(n) time O(1) space):

int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int slow = 0;  // slow points to end of deduped section
    for (int fast = 1; fast < nums.length; fast++) {
        if (nums[fast] != nums[slow]) nums[++slow] = nums[fast];
    }
    return slow + 1;
}

2.2 Linked List: Value in Composition, Not Solo

Nodes stored discretely, linked by pointers. Given node reference, insert/delete O(1); but search O(n). Java's LinkedList is doubly-linked, O(1) at both ends, implements Deque.

// Doubly-linked node
static class Node<E> {
    E item;
    Node<E> prev;
    Node<E> next;
}

"Linked list inserts fast" is half-truth — must first O(n) locate. Memory math: one LinkedList.Node ~24B (12B header + three 12B refs) plus Integer object 16B → storing a 4-byte int actually costs ~40 bytes, 10x bloat . Hence 99% of engineering scenarios ArrayList wins; LinkedList rarely justified solo.

But its highlight is pairing with hash table — Hash table + doubly-linked list = LRU , detailed later. Also appears in: HashMap collision buckets,

LinkedHashMap
accessOrder

chain, Redis quicklist, Netty ChannelPipeline (doubly-linked, O(1) handler add/remove).

Interview must-write: three-pointer list reversal:

ListNode reverseList(ListNode head) {
    ListNode prev = null, curr = head;
    while (curr != null) {
        ListNode next = curr.next;  // ① save next, else break chain
        curr.next = prev;           // ② reverse pointer
        prev = curr;                // ③ prev advances
        curr = next;                // ④ curr advances
    }
    return prev;
}

Also find middle, detect cycle — remember fast-slow pointers : slow moves 1, fast moves 2, meet ⇒ cycle.

2.3 Stack: LIFO's Two Battlefields

Stack operates only at top: push/pop/peek all O(1). Typical: JVM call stack, bracket matching, expression evaluation, non-recursive DFS, undo, monotonic stack.

// Bracket matching, O(n)
boolean isValid(String s) {
    Deque<Character> st = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (c == '(') st.push(')');
        else if (c == '[') st.push(']');
        else if (c == '{') st.push('}');
        else if (st.isEmpty() || st.pop() != c) return false;
    }
    return st.isEmpty();
}

Wrong answer: use java.util.Stack . Better: Stack extends Vector, method-level synchronized hurts performance, iteration order bottom→top contradicts pop semantics — legacy, officially replaced by ArrayDeque. Deep recursion causes StackOverflowError — deep graphs, long lists must rewrite to explicit stack iteration.

Monotonic stack is advanced weapon, essence: Stack stores "indices still awaiting answer"; a larger value pops all smaller ones to settle. Each element pushes/pops at most once → O(n²) brute force drops to O(n). Daily temperatures, next greater element, largest rectangle in histogram — same template:

// Daily temperatures: stack holds indices, temperatures monotonically decreasing
int[] dailyTemperatures(int[] t) {
    int n = t.length;
    int[] res = new int[n];
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 0; i < n; i++) {
        while (!stack.isEmpty() && t[i] > t[stack.peek()]) {
            int prev = stack.pop();
            res[prev] = i - prev;  // answer at pop moment
        }
        stack.push(i);
    }
    return res;
}

2.4 Queue: Interview Really Asks About "That Queue in Thread Pool"

Queue FIFO, scenarios: BFS, producer-consumer, message buffering, rate-limiting sliding window. Array-based queue must handle false overflow — solved by circular queue modulo wrap, which is ArrayDeque 's principle (capacity must be power of 2, because modulo not % but (tail + 1) & (len - 1) bitwise, an order of magnitude faster):

// Circular queue: solves false overflow
public class CircularQueue {
    private final int[] data;
    private int head = 0, tail = 0, size = 0;
    public boolean offer(int val) {
        if (size == data.length) return false;
        data[tail] = val;
        tail = (tail + 1) % data.length;  // modulo wrap, head meets tail
        size++;
        return true;
    }
    public Integer poll() {
        if (size == 0) return null;
        int val = data[head];
        head = (head + 1) % data.length;
        size--;
        return val;
    }
}

Note: ArrayDeque disallows null ; using null as sentinel throws NPE — differs from LinkedList.

Key: Concurrent queue comparison table worth more than definitions:

Implementation          Structure          Lock Design                     Used In
ArrayBlockingQueue      Bounded array      1 lock + 2 Conditions           Strict backpressure needed
LinkedBlockingQueue     Linked list (default unbounded⚠️) putLock / takeLock dual locks, higher throughput newFixedThreadPool (OOM culprit)
SynchronousQueue        Zero capacity, hand-off CAS                       newCachedThreadPool
DelayQueue / DelayedWorkQueue Heap + Leader-Follower Single lock          Scheduled tasks, order timeout
ConcurrentLinkedQueue   Linked list        Lock-free CAS                   High-concurrency non-blocking
Interview follow-up: Why does Alibaba coding guidelines forbid Executors.newFixedThreadPool ? Because it uses unbounded LinkedBlockingQueue (capacity Integer.MAX_VALUE ); downstream slowdown piles tasks, old gen fills, Full GC then OOM. Correct: new ThreadPoolExecutor(...) explicitly pass bounded queue + rejection policy + queue water-level monitoring .

To show concurrency depth, hand-write a bounded blocking queue; essence in wait/notify:

class BlockingQueue<T> {
    private final Object[] items;
    private int head, tail, count;
    BlockingQueue(int cap) { items = new Object[cap]; }
    public synchronized void put(T x) throws InterruptedException {
        while (count == items.length) wait();  // must be while, prevent spurious wakeup
        items[tail] = x;
        tail = (tail + 1) % items.length;
        count++;
        notifyAll();
    }
    public synchronized T take() throws InterruptedException {
        while (count == 0) wait();
        T x = (T) items[head];
        items[head] = null;
        head = (head + 1) % items.length;
        count--;
        notifyAll();
        return x;
    }
}

Note while not if for wait condition — spurious wakeup detail is a bonus point.

3. Hash Table: Explain JDK 8's Three Optimizations and You Win

Hash table trades space for time: hash(key) locates bucket, collisions resolved by chaining or open addressing; avg O(1), worst O(n). Core trilogy: Perturb → Locate → Collision Handling .

3.1 JDK 8 HashMap's Three Gems

// ① Perturb: high 16 bits XOR low 16 bits, letting high bits participate
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// ② Locate: capacity power of 2, modulo degrades to bitwise AND
int index = (n - 1) & hash;
Why perturb? Because (n-1) &amp; hash only uses low bits — when table small, high bits never reach bucket index; without perturb, collisions cluster.

③ High-low bit split during resize is JDK 8's most elegant stroke. When oldCap=16 grows to 32, a bucket chain doesn't recompute hash; split by hash & oldCap == 0: if 0 stays at original index j (lo chain), else moves to j + oldCap (hi chain), preserving original relative order. Contrast JDK 7 head-insertion reversed order, concurrent resize created cycles pegging CPU at 100%.

Key parameters, each with design rationale:

Parameter                Value   Why
Default capacity         16      Power of 2, tableSizeFor rounds up to power of 2
Load factor              0.75    Space-collision tradeoff; cap * 0.75 happens to be integer
Treeify threshold        8       Poisson distribution: chain length ≥8 probability ≈ 6e-8, fallback not norm
Untreeify threshold      6       Buffer between 6 and 8 avoids repeated treeify↔untreeify thrashing at 7/8
Min treeify capacity     64      Table too small ⇒ collisions due to capacity, should resize first not treeify

Interview counter-question: "That's why HashMap requires power-of-2 capacity; hence pre-size with new HashMap<>((int)(expectedSize / 0.75f) + 1) to avoid multiple resize rehash. Large map one-shot resize causes P99 spikes; Redis uses incremental rehash (dual tables + move a bit per op), ConcurrentHashMap uses multi-thread assisted migration."

3.2 Thread Safety Line Must Be Complete

JDK 7: head-insert + concurrent resize → cyclic list, get infinite loop CPU 100% .

JDK 8: tail-insert fixed cycle, but still loses data (two threads put overwrite same bucket), size inaccurate.

Correct: ConcurrentHashMap — CAS init bucket head + synchronized only locks single bucket + transfer multi-thread assisted resize (using ForwardingNode to let readers help migrate) + CounterCell striped counting (same idea as LongAdder). Lock granularity from "whole table" down to "one bucket".

Classic production accident: Custom object as key must override both hashCode and equals , else logically equal objects land in different buckets → "put in but can't get out" ghost. Similarly, avoid mutable keys, and avoid low-discrimination fields for hashCode (batch of same-prefix keys all collide in one bucket, API RT jumps from 2ms to 200ms).

4. Heap: Array Masquerading as Tree, Specializes in TopK

Heap is complete binary tree: parent ≥ (max-heap) or ≤ (min-heap) children. Because complete binary tree has "no holes", it can be compactly stored in array, zero pointer overhead, cache-friendly — PriorityQueue backing is array, no real new Node needed.

Index:  0  1  2  3  4  5  6
Value: [3, 5, 8, 12, 9, 14, 20]   Min-heap
Index relation: parent = (i-1) >>> 1, left = 2i+1, right = 2i+2

Core ops: insert then siftUp , pop root then take last element to top and siftDown , both O(log n). Build heap is O(n) not O(n log n) (bottom-up siftDown, many bottom nodes but shallow sink) — many answer wrong, correct answer scores points.

// Min-heap siftDown: maintain heap order, O(log n)
void siftDown(int[] heap, int i, int size) {
    while (true) {
        int l = i * 2 + 1, r = l + 1, min = i;
        if (l < size && heap[l] < heap[min]) min = l;
        if (r < size && heap[r] < heap[min]) min = r;
        if (min == i) break;
        int t = heap[i]; heap[i] = heap[min]; heap[min] = t;
        i = min;
    }
}
void buildHeap(int[] arr) {
    for (int i = arr.length / 2 - 1; i >= 0; i--) siftDown(arr, i, arr.length);
}

TopK: Heap's Correct Opening

Mnemonic: Find largest K → use min-heap; root is "threshold", smaller ones discarded.

// 10M items, take largest 100: don't sort! O(n log K) time + O(K) memory
static int[] topK(int[] nums, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
    for (int x : nums) {
        if (minHeap.size() < k) minHeap.offer(x);
        else if (x > minHeap.peek()) { minHeap.poll(); minHeap.offer(x); }
    }
    return minHeap.stream().mapToInt(Integer::intValue).toArray();
}

Vs full sort O(n log n) + O(n) memory, directly avoids OOM. Larger data (distributed) → each shard local TopK then merge.

Common pitfalls: PriorityQueue iterator and toString() are not ordered ! Heap only guarantees root extremum (partial order); ordered output requires repeated poll.

Don't write max-heap as (a, b) -> b - a — integer overflow teaches lesson; use Comparator.reverseOrder(). PriorityQueue not thread-safe ; multi-thread use PriorityBlockingQueue.

Heap doesn't support efficient arbitrary element update: priority change breaks heap order. Solution: "lazy delete" (mark + validate on pop), or maintain id → node index for decreaseKey.

Massive scheduled tasks: heap O(log n) sink causes latency spikes; Netty/Kafka use hierarchical timing wheels , insert near O(1).

Streaming median uses dual heaps : max-heap stores smaller half + min-heap stores larger half, keep size diff ≤ 1, median is root combination.

5. Three Ordered Brothers: BST, B+ Tree, Skip List

These three often asked together; clarifying their division of labor locks the win.

5.1 BST & Red-Black Tree: Insurance for "Worst Case"

BST left-smaller right-larger, in-order traversal yields sorted sequence. Lookup strictly O(h) (tree height) not O(log n) — sequential insert 1,2,3,4,5 degenerates to linked list, query O(n). Saying BST is O(log n) guarantees interviewer will ask "Balanced?".

Engineering answer: self-balancing trees:

AVL                    Red-Black
Balance strictness  Height diff ≤ 1, faster reads  Approx balanced (longest path ≤ 2× shortest)
Insert rotations    Max 2                    Max 2
Delete rotations    Possible O(log n) times  Max 3
Suitable            Read-heavy, writes rare  Read-write balanced (JDK chooses it)

Red-black five properties shortest: root black, leaves (NIL) black, no adjacent reds, every path same black-height, nodes either red or black → height ≤ 2log(n+1). So TreeMap, HashMap treeify both choose it. TreeMap 's floorKey / ceilingKey / subMap for in-memory range leaderboards.

Hand-written BST validation classic trap: Cannot use parent-child local comparison, misses ancestor constraints ; must use in-order traversal verify strictly increasing:

boolean isValidBST(TreeNode root) {
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode prev = null;
    while (root != null || !stack.isEmpty()) {
        while (root != null) { stack.push(root); root = root.left; }
        root = stack.pop();
        if (prev != null && root.val <= prev.val) return false;
        prev = root;
        root = root.right;
    }
    return true;
}

5.2 B+ Tree: Not "Tree Victory", But "Disk I/O Victory"

B+ tree multi-way balanced: Non-leaf nodes store only indexes, not data (single page holds hundreds/thousands of keys, tree extremely short), Leaf nodes store all data and are linked by doubly-linked list (range queries slide along list).

B+ Tree structure
B+ Tree structure

Interview numbers most convincing, here's the math:

InnoDB page = 16KB
Non-leaf entry = PK 8B + page_no 6B = 14B  →  16384/14 ≈ 1170 fanout
Leaf page assume 1KB/row  →  16 rows/page
Three levels: 1170 × 1170 × 16 ≈ 21.9M rows
→ Any row lookup needs 3 I/Os, root often resident in Buffer Pool, actual ≈ 1-2 disk I/Os

Why not others? Comparison table worth memorizing:

Candidate          Elimination Reason
Red-Black / AVL    Binary ⇒ fanout 2 ⇒ 20M data height 24 ⇒ 24 random I/Os, DB can't bear
Hash index         Equality O(1) nice, but no range, sort, leftmost prefix
B-Tree             Non-leaf also stores data ⇒ smaller fanout, taller tree; range query needs in-order backtrack, inferior to leaf linked list
Skip List          Nodes physically discrete, each hop a random I/O; B+ tree one node = one page = one I/O

Derived practical points for daily SQL:

InnoDB clustered index leaf stores full row, secondary index leaf stores PK → back-table ; use covering index to avoid back-table.

Composite index obeys leftmost prefix ; avoid functions/implicit conversion on indexed columns, range condition last, no leading %like, else index invalid.

Deep pagination LIMIT 1000000, 10 painfully slow → change to cursor pagination WHERE id > ? — essence leverages leaf ordered linked list.

PK recommend auto-increment or trend-increasing (Snowflake ID) : random PK inserts cause frequent page splits and fragmentation, write amplification; combine with proper fill factor, periodic OPTIMIZE TABLE.

5.3 Skip List: "Coin Flip" Buys Concurrency Freedom

Skip list builds multi-level indexes on ordered linked list; search from top level slide right, hit wall then drop down, expected O(log n) — gives binary search capability to a list that can't binary search .

Skip List structure
Skip List structure

Each node promotes to next level with probability p (usually 1/2 or 1/4), expected levels O(log n). p = 0.25 not arbitrary — it makes expected space overhead ~ 1.33n pointers , less than red-black tree, and no rotations, no recursion .

Skip list is high-frequency hand-write interview question; complete core code:

public class SkipList {
    private static final int MAX_LEVEL = 16;
    private static final double P = 0.25;  // promotion probability, expected levels log(1/P)
    private final Node head = new Node(-1, MAX_LEVEL);
    private int level = 0;

    static class Node {
        int val; Node[] next;
        Node(int v, int lv) { val = v; next = new Node[lv]; }
    }

    // Random level: geometric distribution, amortized O(log n)
    private int randomLevel() {
        int lv = 1;
        while (Math.random() < P && lv < MAX_LEVEL) lv++;
        return lv;
    }

    public void insert(int val) {
        Node[] update = new Node[MAX_LEVEL];
        Node cur = head;
        // 1. Top-down record predecessor at each level
        for (int i = level - 1; i >= 0; i--) {
            while (cur.next[i] != null && cur.next[i].val < val) cur = cur.next[i];
            update[i] = cur;
        }
        // 2. New level exceeds current, pad predecessors with head
        int lv = randomLevel();
        if (lv > level) {
            for (int i = level; i < lv; i++) update[i] = head;
            level = lv;
        }
        // 3. Insert layer by layer, rewire pointers
        Node node = new Node(val, lv);
        for (int i = 0; i < lv; i++) {
            node.next[i] = update[i].next[i];
            update[i].next[i] = node;
        }
    }

    public boolean search(int val) {
        Node cur = head;
        for (int i = level - 1; i >= 0; i--)
            while (cur.next[i] != null && cur.next[i].val < val) cur = cur.next[i];
        return cur.next[0] != null && cur.next[0].val == val;
    }
}

Why concurrent ordered map doesn't use red-black tree? This question is free points: Red-black tree rotations are global structural adjustments across multiple nodes, hard to make fine-grained lock-free; skip list insertion only affects adjacent nodes' next pointers, naturally suits CAS per-level linking + mark deletion , achieving fully lock-free. Trade-off: size() must traverse count, not O(1); worst-case O(n), probabilistic balance.

JDK's ConcurrentSkipListMap is skip list (many don't know, mentioning scores); its random level uses ThreadLocalRandom.nextSecondarySeed() — no global Random , avoids seed CAS contention, zero competition :

// ConcurrentSkipListMap random level idea (JDK source simplified)
int rnd = ThreadLocalRandom.nextSecondarySeed();
if ((rnd & 0x80000001) == 0) {  // highest and lowest bits both 0 → promote
    int level = 1;
    while (((rnd >>>= 1) & 1) != 0) ++level;  // each level prob ≈ 1/4, expected levels 1.33
}

Redis skip list uses p = 1/4, capped at 32 levels. Bonus classic follow-up: Why HashMap treeify doesn't use skip list? Bucket elements usually single-digit; skip list's multi-level pointer overhead not worth it, and random level variance high on tiny data; red-black tree guarantees worst-case O(log n) with hard bound, node only needs 3 pointers.

6. Graph: Only Solution for Relational Problems

Graph = vertices + edges. Storage selection: Sparse graph uses adjacency list ( Map<Integer, List<Edge>>, O(V+E) space), Dense graph uses adjacency matrix (O(V²) space but edge check O(1)), extreme cases CSR. Four algorithm suites:

Scenario                              Algorithm                              Complexity
Maven / Spring Bean load order, course prerequisites  Topological sort (Kahn / DFS, detects cycles)  O(V+E)
Shortest path (navigation, routing)   Dijkstra + heap optimization / A*      O(E log V)
Friend recommendation, gang fraud, connected components  BFS layering / Union-Find / Louvain      O(V+E)
Minimum spanning tree (wiring cost)   Kruskal + Union-Find                   O(E log E)

Must-remember pitfalls:

Cycles must have visited marking , else infinite loop; visited must be marked before recursion/enqueue — key pruning.

Dijkstra cannot handle negative weights , negative weights switch to Bellman-Ford / SPFA.

100k-depth graph recursion guaranteed StackOverflowError, rewrite to explicit ArrayDeque iteration.

Adjacency matrix explodes memory when V large; big graphs use sharding + graph engines (GraphX / Neo4j).

Topological sort via Kahn, also detects cycles (course schedule):

int[] findOrder(int numCourses, int[][] prerequisites) {
    List<List<Integer>> g = new ArrayList<>();
    int[] indeg = new int[numCourses];
    for (int i = 0; i < numCourses; i++) g.add(new ArrayList<>());
    for (int[] p : prerequisites) { g.get(p[1]).add(p[0]); indeg[p[0]]++; }
    Queue<Integer> queue = new ArrayDeque<>();
    for (int i = 0; i < numCourses; i++) if (indeg[i] == 0) queue.offer(i);
    int[] order = new int[numCourses];
    int idx = 0;
    while (!queue.isEmpty()) {
        int u = queue.poll();
        order[idx++] = u;
        for (int v : g.get(u)) if (--indeg[v] == 0) queue.offer(v);
    }
    return idx == numCourses ? order : new int[0];  // dequeued < vertices ⇒ cycle
}

Union-Find for connectivity, path compression + union by rank , actual complexity ≈ O(1):

class UnionFind {
    private final int[] parent, rank;
    UnionFind(int n) {
        parent = new int[n]; rank = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;
    }
    int find(int x) {  // one find, flattens entire chain
        if (parent[x] != x) parent[x] = find(parent[x]);
        return parent[x];
    }
    boolean union(int a, int b) {
        int ra = find(a), rb = find(b);
        if (ra == rb) return false;  // cycle detected
        if (rank[ra] < rank[rb]) { int t = ra; ra = rb; rb = t; }
        parent[rb] = ra;
        if (rank[ra] == rank[rb]) rank[ra]++;
        return true;
    }
}

Graph shadows in engineering more than imagined: Spring Bean dependencies = topological sort, cycle detected = circular dependency — bonus: Spring uses three-level cache ( singletonObjects / earlySingletonObjects / singletonFactories) to solve setter circular dependency, but constructor circular dependency unsolvable , throws BeanCurrentlyInCreationException because object not yet created, can't expose reference early.

7. Hand-Write Section: Three Questions Stringing Knowledge Together

Talk without practice is fake. These three cover most prior knowledge, real high-frequency at ByteDance, Alibaba.

7.1 Hand-Write LRU: Hash + Doubly-Linked List's Moment of Glory

LRU is data structure composition masterpiece: Hash handles "findable" (O(1) locate), doubly-linked list handles "movable" (O(1) reorder/evict) , two O(1) combined = LRU.

class LruCache<K, V> {
    static class Node<K, V> { K k; V v; Node<K,V> prev, next;
        Node(K k, V v) { this.k = k; this.v = v; } }
    private final Map<K, Node<K,V>> idx = new HashMap<>();
    // Double sentinel: eliminates all head/tail null checks, halves bugs
    private final Node<K,V> head = new Node<>(null, null);
    private final Node<K,V> tail = new Node<>(null, null);
    private final int cap;
    LruCache(int cap) { this.cap = cap; head.next = tail; tail.prev = head; }
    V get(K k) {
        Node<K,V> n = idx.get(k);
        if (n == null) return null;
        moveToHead(n);  // hit = "renew life" to head
        return n.v;
    }
    void put(K k, V v) {
        Node<K,V> n = idx.get(k);
        if (n != null) { n.v = v; moveToHead(n); return; }
        if (idx.size() == cap) {
            Node<K,V> lru = tail.prev;
            unlink(lru);
            idx.remove(lru.k);  // only unlink not remove index = memory leak, high-frequency crash point
        }
        Node<K,V> add = new Node<>(k, v);
        idx.put(k, add); linkAfterHead(add);
    }
    private void moveToHead(Node<K,V> n) { unlink(n); linkAfterHead(n); }
    private void unlink(Node<K,V> n) { n.prev.next = n.next; n.next.prev = n.prev; }
    private void linkAfterHead(Node<K,V> n) {
        n.next = head.next; n.prev = head; head.next.prev = n; head.next = n;
    }
}

Real production don't hand-write; JDK provides LinkedHashMap, three lines — but must explain it's exactly the above:

class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;
    LRUCache(int capacity) {
        super((int)(capacity / 0.75f) + 1, 0.75f, true);  // accessOrder=true: get counts as access
        this.capacity = capacity;
    }
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;  // auto-evict least recently used when over capacity
    }
}

Must add: It's not thread-safe. Concurrency: either external lock ( ConcurrentHashMap + segmented list), or use Caffeine (W-TinyLFU, more scan-resistant than LRU).

7.2 Two Stacks Implement Queue & Two Queues Implement Stack

Small points: two stacks simulate queue (one in-stack one out-stack, out-stack empty then pour, amortized O(1)); two queues simulate stack (each push then move front elements to rear).

7.3 O(1) Delete Random Element

LeetCode 380 idea worth remembering: Dynamic array + hash map (value → index) , delete by overwriting removed position with last element then shrink size — array gives O(1) random access, hash gives O(1) locate, another composition exemplar.

8. High-Frequency Pain Points & Solutions Cheat Sheet

Final scattered pits collected into one table, usable for interview finale and production troubleshooting:

Pain Point                  How It Crashes in Production                              Solution
Hash collision degeneration Malicious keys / same-prefix keys all hit one bucket, RT from 2ms to 200ms  Perturb function + ≥8 && ≥64 treeify fallback + rewrite good hashCode/equals
HashMap concurrency         JDK7 resize cycle CPU 100%; JDK8 silent data loss          ConcurrentHashMap: CAS init bucket + lock bucket head + assisted resize + CounterCell striped counting
Large Map resize thrashing  One-shot rehash stalls, P99 spikes                       Pre-estimate capacity; Redis incremental rehash; CHM multi-thread migration
"LinkedList insert fast" illusion Locate O(n) + node header overhead + cache all misses  Most scenarios ArrayList; queue ArrayDeque; LRU LinkedHashMap/Caffeine
Unbounded queue pile-up     Full GC → OOM                                            Bounded queue + rejection policy + queue water-level alert + upstream rate limiting
Massive TopK                Full sort 10M directly OOM                               Fixed-capacity min-heap O(n log K); distributed: shard local TopK then merge
BST degeneration            Sequential insert becomes linked list, O(log n) → O(n)     Red-black/AVL; static data: sort then recursive mid-point balanced build
Ordered structure concurrency hard Red-black rotations can't fine-grain lock          Skip list local CAS: ConcurrentSkipListMap / Redis ZSet
Disk random I/O             Red-black 20 levels ≈ 20 I/Os                            B+ tree fanout ~1000, 3-4 levels; leaf linked list handles range scan; covering index avoids back-table
B+ tree page splits         Random PK inserts frequent splits, write amplification     Auto-increment/Snowflake ID, proper fill factor, periodic OPTIMIZE TABLE
Deep graph recursion stack overflow 100k dependency chain DFS direct SOF              Explicit ArrayDeque iteration; negative weights → Bellman-Ford
False sharing               Multi-core counter performance degrades                    Cache line padding @Contended, LongAdder striping
Massive scheduled tasks     Heap O(log n) sink causes latency spikes                 Hierarchical timing wheels (Netty/Kafka), insert near O(1)
Circular dependency         Startup failure / load order chaos                       Topological sort cycle detection + Spring three-level cache; architecturally extract common Bean to break cycle

9. Five Interviewer Favorite Follow-Up Questions (With Answers)

Why is HashMap capacity power of 2? (n-1) & hash equals modulo but much faster; resize elements only stay at original index or "original + oldCap", enabling high-low bit split without rehashing.

MySQL uses B+ tree, Redis ZSet uses skip list — contradictory? No, constraints differ: DB targets disk pages, needs large fanout, few levels, leaf sequential scan; Redis all in-memory, no I/O pressure, prefers simple implementation + ZRANGE ordered traversal + concurrent local modifications — skip list fits. ZSet internally: skip list handles ordering, dict handles member→score O(1) locate , each does its job.

Is ArrayList always faster than LinkedList? Vast majority yes, cache locality + object header overhead decide. Only "already have node reference, pure head insert/remove" linked list wins, and for that I'd write custom doubly-linked list, not LinkedList.

Why not AVL over Red-Black? AVL delete rotations may be O(log n) times, red-black max 3; read-write balanced scenarios red-black overall better, so JDK chose it.

Tech selection for high-concurrency leaderboard? Redis ZSet for real-time sort and ZREVRANGE, local hotspot fallback ConcurrentSkipListMap; if only Top100 not full ranking, min-heap + periodic snapshot cheaper. Core remains: Ask access pattern first, then pick data structure.

Closing

You'll realize these 10 structures need no rote memorization. Selection essence is always trade-offs among CPU cache hits, disk I/O count, concurrency lock granularity : array wins cache, B+ tree wins fewer I/Os, skip list wins finer locks, heap wins no tree building, hash trades space for time. No best data structure, only the one placed at the right layer.

Three landing suggestions: 1) Drill LRU hand-write, heap siftUp/siftDown, HashMap treeify thresholds into muscle memory — extremely high hit rate; 2) Review your project's new HashMap<>() and thread pool queues — pre-size where needed, bound where needed; 3) Bookmark this comparison table, pull it out at next design review.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion