SteelReed

Search

Search posts, questions…

2. Data Structures & Algorithms

Linear data structures: arrays, linked lists, stacks and queues

Why the same loop runs in 3 ms or 5 seconds: what each array, linked list, stack and queue operation costs on real code paths, how to choose, and how to review AI-written code that picks the wrong structure.

17 Nov 20267 min readJunior

–

1. The problem

A batch job walks 100,000 orders with for (int i = 0; i < orders.size(); i++) orders.get(i) in a few milliseconds. Switch ArrayList to LinkedList "for fast inserts" and it takes about 5 seconds. A queue built on ArrayList.remove(0) drains 100,000 jobs in ~370 ms; ArrayDeque.poll() takes under 2 ms.

2. Key idea

An array puts elements in adjacent cells: cell i is at base + i * size, reached directly, and the CPU preloads a whole 64-byte cache line. A linked list scatters nodes across the heap: reaching element i means walking i nodes, each step possibly a cache miss (~100 ns, versus ~1 ns for L1).

Operation Dynamic array Linked list Stack, queue
Read element i O(1) O(n) n/a
Add, remove at the end O(1) amortized O(1) with a tail O(1)
Add, remove at the front O(n), shift everything O(1) O(1)
Insert in the middle O(n) O(1) once you have the node, finding it O(n) n/a
Full scan sequential, very fast pointer chasing, many times slower pop until empty

2.1 Which structure?

List the operations on the hot path and pick the structure that makes the most frequent one cheap. When Big-O ties, arrays win thanks to the cache.

Structure Use when Don't use when
ArrayList default: index reads, appends, iteration constant adds/removes at the front
ArrayDeque stacks, queues, both ends you need get(i); several threads share it
ArrayBlockingQueue multi-threaded producer/consumer with a bound a single thread
LinkedList rare: in-place insert/delete through a ListIterator almost everything else
LinkedHashMap LRU cache (doubly linked list + hash)

3. In Java

JAVA
List<Order> orders = new ArrayList<>();      // the default
for (Order o : orders) process(o);           // for-each: O(n) for any List
 
Deque<String> stack = new ArrayDeque<>();    // LIFO
stack.push("a");
stack.push("b");
stack.pop();                                 // "b"
 
Queue<Job> jobs = new ArrayDeque<>();        // FIFO
jobs.offer(job);                             // add at the tail
Job next = jobs.poll();                      // take the head, null if empty
 
// Avoid on hot paths:
// for (int i = 0; i < linked.size(); i++) linked.get(i);  // O(n²)
// arrayList.remove(0);                                     // O(n) each time

Don't use java.util.Stack or Vector in new code. Other languages: Python's list.pop(0) shifts the whole array, use collections.deque; Go slices and C#'s List<T> are dynamic arrays too.

4. Working with AI

Hand to AI: JMH benchmarks with production-sized data, edge-case tests (empty, one element, insert at head, remove at tail) for hand-written structures, reading profiler output.

Check yourself in AI-written code:

  • No get(i) in a loop over a LinkedList or over a List of unknown implementation.
  • No ArrayList.remove(0) or add(0, x) used as a queue.
  • Queues shared between threads are BlockingQueues; bounded queues handle offer returning false.
  • Every "faster" claim comes with measurements on realistic data.

5. Exercises

Exercise 1: Review isBalanced

The AI says "O(n), handles every case, tested with ([]{}) and (]". Find the bug, name a test that proves it, fix it.

JAVA
static boolean isBalanced(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (c == '(' || c == '[' || c == '{') stack.push(c);
        else if (c == ')' || c == ']' || c == '}') {
            if (stack.isEmpty() || stack.pop() != matching(c)) return false;
        }
    }
    return true;
}
Solution 1

The last line returns true without checking for unclosed brackets left on the stack. "(()" and "(((" both count as valid. Both AI tests empty the stack, so they miss it.

Test: assertFalse(isBalanced("(()")). A full set covers three failure kinds: closing before opening "())", wrong type "(]", unclosed "(()", plus the empty string returning true.

Fix: return stack.isEmpty();.

Exercise 2: Read an incident

A report export endpoint had a 60 ms p99 for six months. A large customer imports 150,000 rows; p99 jumps to 9 seconds, one CPU core at 100%, no errors in the log. Profiler: 94% of time in java.util.LinkedList.node(int), called from ReportService.render. Diagnose it, say what to do in 15 minutes, fix the root cause.

Solution 2
  • render loops for (int i...) rows.get(i) over a LinkedList. node(int) is the part of get that walks to the element: O(n) each time, O(n²) for the loop, about 5.6 billion steps for 150,000 rows.
  • 15 minutes: cap rows per export or move large exports to a background job.
  • Root fix: for-each (O(n) on any List), and create the list as an ArrayList. Add a performance test with 200,000 rows.

Summary

  • Arrays read element i in O(1); linked lists take O(n) to walk there.
  • Linked-list insert/delete is O(1) only when you already hold the node.
  • Thanks to the cache, ArrayList usually beats LinkedList even at equal Big-O.
  • Java: default ArrayList; stacks and queues use ArrayDeque; multiple threads use a BlockingQueue.
  • When reviewing, look for get(i) in loops and remove(0) used as a queue.

Further reading: List, Set, Map.

Practice interview questions on this topic

All Collections & DSA questions →

Loading comments…