Skip to content

Data Structures

A data structure is a contract between how you store data and how fast you can answer questions about it. Interviews rarely ask you to write a red-black tree; they ask a question whose shape makes one structure obvious, and watch whether you pick it.

Arrays give O(1) index access and are the default. Linked lists give O(1) insert and delete at a known node but O(n) lookup, and are rarely right outside LRU caches. Hash tables give O(1) average lookup and are the most common interview win — memory for time. Trees keep order, so you get O(log n) search, min/max and ranges. Heaps give O(1) min/max and O(log n) insert and extract. Graphs model relationships, traversed with BFS or DFS. Tries are for prefixes.

Need Structure Lookup Insert Delete
Indexed access, iteration Array O(1) O(1) append, O(n) middle O(n)
Insert/delete at known node Linked list O(n) O(1) O(1)
Membership, counting Hash table / set O(1) avg O(1) avg O(1) avg
LIFO Stack O(n) O(1) O(1)
FIFO Queue / deque O(n) O(1) O(1)
Ordered search, min/max, ranges Balanced BST O(log n) O(log n) O(log n)
Repeated min/max Heap O(1) peek O(log n) O(log n)
Prefix search, autocomplete Trie O(k) O(k) O(k)

Contiguous memory, O(1) random access, O(n) insert or delete at the front (unshift, insert). Dynamic arrays over-allocate and double when full, making append O(1) amortised; indexing is arr[i].

Strings are arrays of characters with a trap: repeated concatenation allocates a new object each time, so result = result + chunk in a loop is O(n²). Build with result << chunk on a mutable buffer (+"" gives an unfrozen copy), or collect and join. Most string problems reduce to a 26- or 128-slot count array: O(n) time, O(1) space, no hashing.

A node holds a value and a next pointer. O(1) insert and delete given the node, no reallocation, but O(n) access and poor cache locality. Reversing a list is three local variables — prev, node, next — reassigned in a loop; get that right and most list problems follow. Classic uses: LRU cache (hash map + doubly linked list), merging sorted lists, cycle detection with Floyd’s tortoise and hare, finding the middle node with slow/fast pointers.

Stacks and queues are both O(1) if built correctly: a stack is LIFO (push/pop on an array), a queue is FIFO. In Ruby Array#shift is O(n), so a BFS using shift is O(n²) — use an index pointer or a real deque. Ruby ships neither a heap nor a deque; saying so is a good answer.

A hash function maps a key to a bucket; collisions are resolved by chaining or open addressing. Average O(1); worst case O(n) if every key collides. Ruby’s Hash keeps insertion order and offers defaults that do not mutate the hash on read: Hash.new(0) for counters, Hash.new { |h, k| h[k] = [] } for grouped buckets.

Keys must be hashable and stable — mutating an object after using it as a key corrupts lookups.

A binary search tree holds left < node < right, giving O(h) search: O(log n) balanced, O(n) degenerate. Traversals matter more than implementations: in-order yields sorted output, pre-order clones, post-order evaluates or deletes, level-order is BFS.

class BST
Node = Struct.new(:value, :left, :right)
def initialize = @root = nil
def insert(value) = @root = insert_at(@root, value)
def include?(value)
node = @root
while node
return true if node.value == value
node = value < node.value ? node.left : node.right
end
false
end
private
def insert_at(node, value)
return Node.new(value, nil, nil) if node.nil?
if value < node.value
node.left = insert_at(node.left, value)
else
node.right = insert_at(node.right, value)
end
node
end
end

Balanced variants (AVL, red-black, B-tree) add rotations to keep height logarithmic. Know that databases use B-trees for range scans, and that a sorted array plus binary search often replaces a BST.

A binary heap is a complete tree in an array: the children of index i are 2i + 1 and 2i + 2, the parent is (i - 1) / 2. O(1) peek at the extremum, O(log n) insert and extract, but the rest of the array is not sorted. Uses: top-k (heap of size k → O(n log k)), Dijkstra, merge k lists, running median with two heaps.

Store graphs as an adjacency list (sparse, O(V + E)) or matrix (dense, O(V²)). BFS gives shortest paths in unweighted graphs; Dijkstra handles non-negative weights; Bellman-Ford handles negatives and detects negative cycles.

A trie stores strings by prefix: O(k) operations in the key length, independent of how many keys are stored, at the cost of one node per distinct key prefix. A node is a hash of character to child plus an end-of-word flag. Use it for autocomplete, spell check and IP routing tables.

  1. Why choose a tree over a hash table here?
  2. What happens when the hash table load factor exceeds 1?
  3. How would you support decrease-key in a heap?
  4. When does a balanced BST beat a skip list?
  5. Can you solve this with O(1) extra space instead of a hash map?
  • Array#shift in a BFS loop. O(n) each time makes the traversal O(n²).
  • Assuming hash tables are always O(1). Worst case is O(n).
  • Choosing a BST when a hash map suffices, or vice versa: one gives order, the other speed.
  • Confusing a heap with a sorted structure. Only the root is guaranteed.
  • Mutating a hash key after insertion. The bucket is stale and lookups break.