Data structures interview questions with complexity tables and code

Data structures interview questions test whether you know how each structure stores data, what its operations cost, and which one to reach for when a problem needs fast lookup, ordering, the smallest element or prefix search. Expect questions on arrays, linked lists, stacks and queues, hash maps, trees, heaps, graphs and tries, often as a short coding task where choosing the right structure is most of the answer. State the time and space complexity of every operation you use, including the worst case.

By Published 10 min read

What data structure rounds look like

Few interviews ask "define a linked list" and stop. Most fold data structures into coding problems: the interviewer describes a task, and the real question is whether you pick a hash map, a heap or a stack before writing a line. Fresher and campus rounds add direct theory questions and complexity tables. Experienced rounds expect you to compare options aloud, mention memory and cache behavior, and know how your language's built-in collections behave. This page stays on the structures themselves; algorithm families such as sorting, dynamic programming and shortest paths are a separate topic and appear here only where a structure depends on them.

Time complexity of common operations (n elements; average case unless stated)
StructureAccess / lookupInsertDeleteNotes
Array (fixed)O(1) by index; O(n) searchO(n) in the middleO(n) in the middleContiguous memory, cache friendly
Dynamic arrayO(1) by indexO(1) amortized at end; O(n) on a resizeO(1) at endPython list, Java ArrayList, JS array
Singly linked listO(n)O(1) at head or after a known nodeO(1) after a known nodeNeeds the previous node to unlink
Doubly linked listO(n)O(1) at either end or a known nodeO(1) for a known nodeExtra pointer per node
Stack / queue / dequeO(1) top or endsO(1)O(1)Use a deque, not list.pop(0)
Hash map / setO(1) average, O(n) worstO(1) averageO(1) averageNo ordering by key
Balanced BSTO(log n)O(log n)O(log n)Sorted order, range queries
Binary heapO(1) peek min/max; O(n) searchO(log n)O(log n) popBuild from n items in O(n)
TrieO(L) for a key of length LO(L)O(L)Prefix queries; memory heavy
Graph (adjacency list)O(degree) edge checkO(1) add edgeO(degree)Space O(V + E)
Time complexity of common operations (n elements; average case unless stated). Scroll sideways on a small screen.

Arrays, strings and linked lists

  • Why is appending to a dynamic array O(1) amortized and not always O(1)? When it is full it allocates a larger block (often about 1.5 to 2 times) and copies everything. Because growth is geometric, the total copy work over n appends stays proportional to n.
  • Array or linked list? Arrays win on index access and on cache locality, which makes them faster in practice for most workloads. Linked lists win when you insert or remove at known positions often and never need random access.
  • How do you find the middle of a linked list in one pass? Two pointers: slow moves one node, fast moves two; when fast reaches the end, slow is in the middle.
  • How do you detect a cycle in a linked list? The same fast and slow pointers. If they ever meet, there is a cycle; O(n) time and O(1) space, unlike storing visited nodes in a set.
  • Why are strings immutable in Java, Python and JavaScript, and what does it cost? Immutability makes strings safe to share and hash. Building a string with repeated += in a loop can copy the whole string each time, so use a list and join, or a StringBuilder.
  • What is a sentinel (dummy) head node for? It removes the special case of inserting or deleting at the head, which shortens linked list code and its bugs.
  • How does a circular buffer work? A fixed array with head and tail indexes that wrap around with modulo. It gives a bounded queue with O(1) operations and no allocation.
class Node:
    def __init__(self, val, next=None):
        self.val, self.next = val, next


def reverse(head):
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev


def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out


print(to_list(reverse(Node(1, Node(2, Node(3))))))  # [3, 2, 1]
Reversing a singly linked list in place: O(n) time, O(1) extra space.

Stacks, queues and hash maps

Questions where the structure is the answer
QuestionStructure to reach forWhy
Check that brackets in a string are balanced.StackThe most recent opener must close first: last in, first out.
Implement undo and redo.Two stacksUndo pops from one and pushes to the other; any new action clears redo.
Process jobs in arrival order with a fixed number of workers.QueueFirst in, first out keeps arrival order fair.
Keep the maximum of a sliding window.Deque of indexesDrop smaller values from the back and expired indexes from the front; each index enters and leaves once.
Implement a queue using two stacks.Two stacksPush to an inbox stack; when popping, move everything to an outbox stack only if it is empty. Amortized O(1) per operation.
Find two numbers that add up to a target.Hash mapStore each value's index; for each number, look up target minus number in O(1).
Group words that are anagrams.Hash map of listsKey each word by its sorted letters or letter counts.
Count the most frequent items.Hash map, then a heapCount in O(n); a size-k heap gives the top k without sorting everything.
Build an LRU cache with O(1) get and put.Hash map plus doubly linked listThe map finds the node; the list keeps recency order and evicts from one end.
Questions where the structure is the answer. Scroll sideways on a small screen.
  • How does a hash map work inside? A hash function maps each key to a bucket in an array. Collisions are handled by chaining (a list per bucket) or open addressing (probing for another slot). When the load factor passes a threshold, the table grows and every key is rehashed.
  • Why is the worst case O(n)? If many keys land in one bucket, a lookup scans them all. Good hash functions, resizing, and in some runtimes randomized hashing or tree-shaped buckets keep that rare.
  • What makes a good hash map key? It must be immutable while stored, and equal keys must produce equal hashes. A mutable list as a key in Python is rejected for exactly that reason.
  • Hash set or sorted set? A hash set gives O(1) average membership with no order. A sorted (tree) set gives O(log n) membership plus ordered iteration, floor and ceiling queries.
class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.map = new Map();
  }

  get(key) {
    if (!this.map.has(key)) return -1;
    const value = this.map.get(key);
    this.map.delete(key);
    this.map.set(key, value);          // now the most recently used
    return value;
  }

  put(key, value) {
    if (this.map.has(key)) this.map.delete(key);
    this.map.set(key, value);
    if (this.map.size > this.capacity) {
      const oldest = this.map.keys().next().value;
      this.map.delete(oldest);         // evict the least recently used
    }
  }
}

const cache = new LRUCache(2);
cache.put("a", 1); cache.put("b", 2); cache.get("a"); cache.put("c", 3);
console.log(cache.get("b"), cache.get("a"), cache.get("c")); // -1 1 3
An LRU cache using a JavaScript Map, which iterates in insertion order. Deleting and re-inserting a key moves it to the most-recent end.
def balanced(s: str) -> bool:
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack


print(balanced("{[()]}"), balanced("([)]"), balanced("(("))  # True False False
Balanced brackets with a stack: O(n) time and O(n) space.

Trees and heaps

  • What is the binary search tree property? Every key in a node's left subtree is smaller than the node and every key in the right subtree is larger, so search can discard half the remaining tree at each step when the tree is balanced.
  • Why do BSTs need balancing? Inserting sorted data into a plain BST produces a linked list with O(n) operations. Self-balancing trees such as AVL and red-black trees keep the height O(log n) with rotations.
  • Which traversal gives sorted output? In-order traversal of a BST (left, node, right). Pre-order is useful for copying a tree, post-order for deleting it, and level-order (with a queue) for printing by depth.
  • How do you check that a binary tree is a valid BST? Pass down the allowed minimum and maximum for each subtree. Comparing each node only with its direct children misses violations deeper down.
  • Height versus depth, and full versus complete? Depth counts edges from the root to a node; height counts edges from a node down to its deepest leaf. A complete tree has every level full except possibly the last, which fills from the left, and that shape is what lets a heap live in an array.
  • How is a heap stored? As an array: the children of index i sit at 2i + 1 and 2i + 2. Push adds at the end and sifts up; pop moves the last item to the root and sifts down, both O(log n).
  • Heap or sorted array or BST for a priority queue? A heap gives O(log n) push and pop with O(1) peek and little overhead. A balanced BST also supports deleting arbitrary items and ordered iteration.
  • How do you keep a running median? Two heaps: a max-heap for the lower half and a min-heap for the upper half, rebalanced so their sizes differ by at most one.
  • What is a B-tree and why do databases use it? A balanced tree with many keys per node, so each node fills a disk page and lookups touch few pages. Database indexes are usually B-tree variants.
import heapq


def k_largest(nums, k):
    heap = []
    for x in nums:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:
            heapq.heapreplace(heap, x)  # pop the smallest, push x
    return sorted(heap, reverse=True)


print(k_largest([5, 1, 9, 3, 7, 9, 2], 3))  # [9, 9, 7]
The k largest values with a min-heap of size k: O(n log k) time and O(k) space, better than sorting when k is small.

Graphs and tries

Intermediate and senior questions
QuestionWhat it testsWhat a strong answer shows
Adjacency list or adjacency matrix?RepresentationA list uses O(V + E) space and suits sparse graphs, which most real ones are. A matrix uses O(V squared) space but answers "is there an edge?" in O(1), which suits small dense graphs.
Directed versus undirected, weighted versus unweighted?VocabularyThe edge type decides the algorithm later: BFS finds shortest paths only when edges are unweighted; weights call for something like Dijkstra's algorithm.
How do you avoid looping forever in a graph traversal?Visited setKeep a visited set (or color array) and skip nodes already seen. Trees do not need it because they have no cycles.
How would you model a social network's "people you may know"?ModelingUsers as nodes, friendships as undirected edges in adjacency sets; friends of friends are two hops away and can be counted with a hash map.
What is a DAG used for?OrderingDependencies with no cycles, such as build steps or course prerequisites. A topological order exists only if the graph is acyclic.
What is a union-find (disjoint set) structure?ConnectivityIt tracks which items belong to the same group with near-constant time union and find, using path compression and union by rank.
When is a trie better than a hash set of words?PrefixesWhen you need prefix queries such as autocomplete or "does any word start with pre". Lookup cost depends on key length, not on how many words are stored.
How do you cut a trie's memory use?OptimizationStore children in a small map instead of a fixed 26-slot array, or compress chains of single-child nodes into one edge (a radix tree).
Intermediate and senior questions. Scroll sideways on a small screen.
class Trie:
    def __init__(self):
        self.children = {}
        self.is_word = False

    def insert(self, word):
        node = self
        for ch in word:
            node = node.children.setdefault(ch, Trie())
        node.is_word = True

    def _walk(self, text):
        node = self
        for ch in text:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word):
        node = self._walk(word)
        return node is not None and node.is_word

    def starts_with(self, prefix):
        return self._walk(prefix) is not None


t = Trie()
for w in ["car", "card", "care"]:
    t.insert(w)
print(t.search("car"), t.search("ca"), t.starts_with("ca"))  # True False True
A trie with insert, exact search and prefix search. Each operation is O(L) for a word of length L.
from collections import deque, defaultdict

edges = [("ana", "ben"), ("ben", "cy"), ("ana", "dee"), ("dee", "cy"), ("cy", "eli")]
graph = defaultdict(set)
for a, b in edges:
    graph[a].add(b)
    graph[b].add(a)


def hops_from(start):
    dist = {start: 0}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for nxt in graph[node]:
            if nxt not in dist:
                dist[nxt] = dist[node] + 1
                queue.append(nxt)
    return dist


print(sorted(hops_from("ana").items()))
# [('ana', 0), ('ben', 1), ('cy', 2), ('dee', 1), ('eli', 3)]
An adjacency list and a breadth-first walk that returns the number of hops from a start node (unweighted graph).

Fictional example

Answering "Design a structure for the top 10 trending hashtags in the last hour"
Interviewer
Posts stream in with hashtags. At any moment I want the ten most used hashtags of the last hour. What structures would you use?
Candidate
I need three things: counts per hashtag, a way to expire old uses, and the top ten. For counts, a hash map from hashtag to count gives O(1) updates. For expiry, a queue of (timestamp, hashtag) pairs in arrival order: when a new post arrives I pop from the front while entries are older than an hour and decrement their counts. Each use enters and leaves the queue once, so that is amortized O(1) per use. For the top ten, I would not keep a sorted structure of every hashtag, since counts change constantly. When asked, I scan the map with a min-heap of size ten, which is O(m log 10) for m distinct hashtags. If queries were far more frequent than posts, I would switch to a balanced tree keyed by count so the top ten are always ordered. To save memory at high volume I could bucket the queue by minute instead of storing every single use.

How to prepare for data structures questions

  1. Build each structure once by handA dynamic array with resizing, a linked list, a hash map with chaining, a binary heap and a trie. Writing them once makes every complexity question easy to reason out.
  2. Learn your language's collectionsKnow which built-in gives you a deque, a heap, an ordered map and a set, and what each operation costs. In Python, for example, list.pop(0) is O(n) and deque.popleft() is O(1).
  3. Practice choosing, not just codingFor each practice problem, say which structure you would use and why before you code. That sentence is what interviewers listen for.
  4. Recite the complexity tableCover the table above and fill it in from memory, including worst cases for hash maps and unbalanced trees.
  5. Then move to algorithmsOnce structures are solid, sorting, recursion, graph search and dynamic programming build directly on them.

Data structures pair with design-level thinking: OOP interview questions covers how to wrap these structures in clean classes, software engineer interview questions shows where coding rounds sit in a full loop, and the search autocomplete design shows a trie at production scale.

Coding rounds are judged on the reasoning you say out loud as much as on the code. During practice, Natively, an AI interview assistant for Mac and Windows, can read a problem from a screenshot and suggest which structure fits and what it costs, and it transcribes your mock session so you can check whether you stated complexity before the interviewer had to ask. With Pro or the free trial, it can also use the résumé and job description you add. You keep the transcript and notes of each session to review.

Questions people ask

What data structures are asked about in interviews?

Arrays and dynamic arrays, linked lists, stacks, queues and deques, hash maps and sets, binary search trees, heaps, graphs and tries. Most questions ask which one fits a problem and what its operations cost.

What is the time complexity of a hash map lookup?

O(1) on average and O(n) in the worst case, when many keys collide in one bucket. Good hashing and resizing keep the worst case rare.

When should I use a heap instead of sorting?

When you only need the smallest or largest items, or items keep arriving. A heap gives O(log n) insert and removal and the top k of n items in O(n log k), cheaper than sorting everything.

How should I prepare for data structures interview questions?

Implement each core structure once by hand, learn what your language's built-in collections cost, practice naming the right structure before coding, and recite the complexity table from memory.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP