Most coding interview problems revolve around a small set of fundamental data structures.
Each one organizes data differently, and how it organizes that data determines which operations are fast and which are slow. Once you understand these trade-offs, choosing the right data structure for a problem becomes much easier.
In this lesson, we'll explore thirteen essential data structures you need to know for coding interviews. For each one, we'll understand how it works, how it's represented, when to use it, and the time complexity of its common operations.
Let's start with the most fundamental data structure: the array.
An array stores elements next to each other in a contiguous block of memory. Each element has a position called an index, which usually starts at zero.
Here's an array containing six numbers.
Since each element occupies the same amount of space, the computer can calculate the memory address of any element directly from its index. This makes accessing or updating an element by index an O(1) operation.
Searching for a value in an unsorted array takes O(n) time because we may need to check every element. But if the array is sorted, we can use binary search to find it in O(log n) time.
Inserting and deleting an element in the middle is more expensive because we need to shift other elements. For example, to insert 10 at index 2, we need to shift 8, 20, 3, and 15 one position to the right.
Similarly, to delete an element, we need to shift all the elements after it one position to the left.
In the worst case, we may need to shift nearly every element in the array, so both insertion and deletion take O(n) time.
Adding or removing an element at the end, on the other hand, requires no shifting.
Dynamic arrays, like ArrayList in Java, vector in C++, and list in Python, automatically allocate a larger block of memory and copy existing elements when they run out of space. Since resizing happens infrequently, appending takes O(1) amortized time.
Loading simulation...
Use an array when you need fast access by index or want to process elements sequentially. Common problem solving techniques like two pointers, sliding window, and prefix sums work directly on arrays.
A matrix is a two-dimensional array that organizes elements into rows and columns. It's typically represented as an array of arrays, where each inner array corresponds to a row.
Here's a matrix with three rows and four columns.
Each cell is identified by two indices: its row index and column index. For example, matrix[1][2] refers to the cell at row index 1 and column index 2.
Accessing any cell takes O(1) time, while traversing the entire matrix takes O(m × n) time, where m is the number of rows and n is the number of columns.
Many matrix problems involve navigating between neighboring cells. From row 1, column 2, we can move up, down, left, or right to reach its four immediate neighbors.
A common technique is to represent these four directions as row and column offsets, iterate through them, and skip any position that lies outside the matrix boundaries.
Matrices are useful whenever data naturally forms a grid, such as a game board, a map, or an image.
They're also commonly used to store intermediate results in dynamic programming. And for grid problems like counting islands, we can treat each cell as a node in a graph.
Next up is the hash map, also commonly known as a hash table or dictionary.
A hash map stores key-value pairs and allows us to quickly retrieve a value using its corresponding key. For example, we could map student names to their scores.
Under the hood, a hash map uses an array of slots called buckets. When we insert a key, a hash function converts it into a number, which is then used to determine which bucket should store the entry.
Loading simulation...
To look up the key later, we compute the same hash and go directly to the corresponding bucket, rather than searching through every entry.
When two different keys map to the same bucket, we have what's called a hash collision.
One common way to handle collisions is chaining, where each bucket maintains a collection of entries, typically using a linked list. Another approach is open addressing, where we probe other slots until we find an available one.
As the hash map fills up, it expands its underlying array and redistributes the entries to reduce collisions and maintain efficient performance.
With a good hash function and proper resizing, insertion, lookup, and deletion take O(1) time on average.
In the worst case, if too many keys collide, these operations can degrade to O(n) time, although good hash functions make this unlikely.
A closely related data structure is the hash set, which stores only keys without associated values. It's useful when we simply need to check whether an element exists.
Hash maps can help us turn many quadratic-time solutions into linear-time solutions by efficiently tracking frequencies and checking membership, eliminating the need for repeated searches.
A linked list stores elements as a chain of connected nodes. Each node contains a value and a pointer to the next node in the list.
Here's a linked list containing 3, 8, 1, and 6. The first node is called the head, and the last node points to null, marking the end of the list.
Unlike an array, these nodes don't need to occupy contiguous memory locations. They can be scattered throughout memory, with pointers connecting them in order.
In a doubly linked list, each node also contains a pointer to the previous node, allowing us to traverse the list in both directions.
Unlike arrays, linked lists don't support direct access by index. To reach the fourth node, we need to start at the head and follow three pointers. As a result, accessing an element by position or searching for a value takes O(n) time in the worst case.
Where linked lists shine is in insertion and deletion.
To insert 5 after 8, we create a new node, point it to the node containing 1, and update 8's pointer to point to the new node.
We only need to update two pointers, without shifting any elements. So the operation takes O(1) time.
Similarly, to delete the node after 8, we simply update 8's pointer to bypass that node.
Both operations take constant time, assuming we already have a reference to the appropriate node. Otherwise, finding that node can take O(n) time.
Inserting or removing an element at the head takes O(1) time. Inserting at the tail also takes constant time if we maintain a tail pointer.
Loading simulation...
Use a linked list when you need frequent insertions and deletions at known positions but don't require fast access by index.
A classic example is an LRU cache, which combines a hash map with a doubly linked list to locate, move, or remove any entry in constant time on average.
Most linked list problems, such as reversing a list, detecting a cycle, or merging two sorted lists, revolve around carefully traversing the list and manipulating its pointers.
A stack is a collection in which the last element added is the first one removed. This ordering is called Last In, First Out, or LIFO.
Loading simulation...
Think of it like the stack of plates in a kitchen, where we add and remove plates from the top.
A stack supports three main operations. Push adds an element to the top, pop removes the top element, and peek lets us access it without removing it. All three operations take constant time.
A stack is typically implemented using a dynamic array, where the last element represents the top, or a linked list, where the head represents the top.
Stacks are useful whenever we need to process the most recent element first or match opening and closing elements.
Common applications include undo functionality, function calls and recursion, iterative depth-first search, and problems like finding the next greater element using the monotonic stack pattern.
A queue works in the opposite way to a stack. The first element added is the first one removed. This ordering is called First In, First Out, or FIFO.
Loading simulation...
Think of it like a line at a ticket counter, where the first person to join the line is the first to get a ticket.
A queue supports two main operations. Enqueue adds an element to the back, while dequeue removes an element from the front.
Both operations are designed to take O(1) time, but the choice of implementation matters.
If we use a regular dynamic array and remove an element from the front, every remaining element needs to shift one position to the left, making dequeue an O(n) operation.
That's why queues are typically implemented using a linked list with head and tail pointers, or a circular array, where the front and rear indices wrap around to reuse available space.
In practice, we can use ArrayDeque in Java, deque from the collections module in Python, or queue in C++.
Use a queue whenever elements need to be processed in the order they arrive.
One of the most common applications of queues in DSA is breadth-first search, where a queue allows us to process nodes closer to the starting node before exploring those farther away.
A deque, short for double-ended queue, is a more flexible version of a regular queue.
Loading simulation...
Unlike a queue, which adds elements at the back and removes them from the front, a deque allows us to add and remove elements from either end. All four operations take O(1) time.
A deque is typically implemented using a doubly linked list or a circular array, allowing efficient operations at both ends without shifting elements.
This flexibility means a deque can function as either a stack or a queue. If we add and remove elements from the same end, it behaves like a stack. If we add elements at one end and remove them from the other, it behaves like a queue.
Use a deque when a problem requires efficient insertions and deletions at both ends of a sequence.
One of its most common applications in DSA is the monotonic deque pattern, which allows us to efficiently track the maximum or minimum element within a sliding window.
For example, in the Sliding Window Maximum problem, we remove elements from the front when they fall outside the window and remove smaller elements from the back when a larger element arrives.
This allows us to find the maximum of every window in O(n) total time.
So far, we've explored linear data structures. Now, let's move on to hierarchical data structures, starting with the binary tree.
A binary tree consists of nodes, where each node can have at most two children, called the left child and the right child. The topmost node is called the root, while nodes without any children are called leaf nodes.
Each node is typically represented as an object containing a value and references to its left and right children. A null reference indicates that the corresponding child doesn't exist.
Visiting every node in a tree is called traversal, and it takes O(n) time. There are four common ways to traverse a binary tree.
Loading simulation...
Preorder visits the current node first, followed by its left subtree and then its right subtree.
Inorder visits the left subtree first, followed by the current node and then the right subtree.
Postorder visits the left and right subtrees before visiting the current node.
And level order uses a queue to visit nodes one level at a time, from left to right, giving us 1 through 6 in order.
Since a regular binary tree doesn't maintain any specific ordering of values, searching for a value can take O(n) time in the worst case.
Binary trees are useful for representing hierarchical structures, such as expression trees and decision trees.
An important property of a binary tree is that each subtree is itself a binary tree. This recursive structure makes recursion a natural way to solve many tree problems. We often solve smaller problems for the left and right subtrees and combine their results to solve the original problem.
For example, the maximum depth of a tree is one plus the greater of its left and right subtree depths, with an empty tree having a depth of zero. For this tree, that gives us three.
Recursive traversals take O(n) time and require extra space proportional to the tree's height, with one call stack frame per level. We can also implement these traversals iteratively using an explicit stack instead of relying on the call stack.
A binary search tree, or BST, is a binary tree that follows an additional ordering rule. For every node, all values in its left subtree are smaller than its value, and all values in its right subtree are larger.
Loading simulation...
This ordering allows us to eliminate an entire subtree at each step of a search, much like binary search.
For example, to find 7, we compare it with 8 and move left to 3. We then move right to 6, and right again to reach 7. We've found our target by visiting just four nodes, without exploring the entire right subtree of 8.
Insertion follows a similar process. We navigate through the tree until we find an empty position where the new node belongs.
Deletion also begins by locating the target node, followed by restructuring the tree as needed to preserve the ordering rule.
Searching, inserting, and deleting all take O(h) time, where h is the height of the tree. In a balanced tree, the height is proportional to log n, giving us O(log n) time for these operations.
However, if we insert 1, 2, 3, 4, and 5 in sorted order, each new node becomes the right child of the previous one. The tree essentially becomes a linked list, causing these operations to degrade to O(n) time.
To avoid this, self-balancing BSTs, such as AVL trees and red-black trees, automatically restructure themselves during insertions and deletions to maintain a height of O(log n).
Java's TreeMap and TreeSet are implemented using red-black trees, as are typical implementations of map and set in C++.
Another useful property of a BST is that an inorder traversal visits all its values in sorted order.
Use a balanced BST when you need to maintain sorted data while supporting frequent insertions and deletions.
It also allows you to efficiently find the smallest value greater than or equal to a target, find the largest value smaller than or equal to a target, or retrieve all values within a given range.
These are operations that a hash map cannot handle efficiently because it doesn't maintain keys in sorted order.
A trie, also known as a prefix tree, stores strings character by character, allowing words with common prefixes to share the same path from the root.
The root represents an empty string, and every node below it represents a character.
Each node stores references to its children, typically using a hash map or an array of 26 slots for lowercase English letters. It also maintains a flag indicating whether a complete word ends at that node.
Loading simulation...
Let's insert four words: car, cart, cat, and dog.
Inserting car creates the path c, a, r, and marks the node r as the end of a word.
cart follows the existing path, adds a new node for t, and marks it as the end of another word.
cat shares the prefix c and a before branching off to its own t, while dog creates an entirely separate branch from the root.
To search for cat, we follow the path c, a, t, and check the end-of-word flag, which confirms that cat exists in the trie.
Now, what happens if we search for ca? The path exists, but the node a isn't marked as the end of a word, so ca itself isn't stored as a complete word.
However, ca is a valid prefix of several stored words, so a prefix check returns true.
Insertion, search, and prefix checks all take O(L) time, where L is the length of the input string, regardless of how many words are stored in the trie, assuming constant-time access to child nodes.
Use a trie when a problem involves working with prefixes, such as implementing autocomplete, finding words with a given prefix, or searching for words on a grid of letters.
A hash set can efficiently tell us whether a complete word exists, but finding all words that share a particular prefix requires scanning its entries.
With a trie, we simply follow the prefix once to reach the corresponding node. Every word in the subtree rooted at that node shares the same prefix.
A heap is a tree-based data structure that provides quick access to the smallest or largest element in a collection.
The most common type is a binary heap, which is structured as a complete binary tree. This means every level is completely filled except possibly the last, which fills from left to right.
Loading simulation...
In a min-heap, every parent is smaller than or equal to its children, ensuring that the smallest element is always at the root. A max-heap follows the opposite rule, keeping the largest element at the root.
Unlike a sorted array, a heap only maintains an ordering between parents and their children. Its elements aren't necessarily sorted overall.
Because the tree is complete, we can efficiently represent it using an array without storing any pointers. For a node at index i, its left and right children are at indices 2i + 1 and 2i + 2, respectively. Its parent is at index (i - 1) / 2, rounded down.
Here's a min-heap represented by an array.
Since the smallest element is always at the root, accessing it takes O(1) time.
To insert a new element, we append it to the array and sift it up, repeatedly swapping it with its parent as long as it's smaller.
For example, if we insert 0, it starts as a child of 2, swaps with 2, and then swaps with 1 to become the new root.
To remove the smallest element, we replace the root with the last element and sift it down, swapping it with its smaller child until the heap property is restored.
Since a complete binary tree has a height of O(log n), both insertion and removal of the root take O(log n) time, excluding occasional array resizing.
Building a heap from n elements at once takes O(n) time using the bottom-up heapify algorithm. However, searching for an arbitrary element takes O(n) time in the worst case.
Most programming languages provide built-in heap implementations, such as PriorityQueue in Java, heapq in Python, and priority_queue in C++.
Use a heap when you repeatedly need to access or remove the smallest or largest element from a collection that keeps changing.
Heaps are commonly used to find the k largest or smallest elements in an array, merge k sorted lists, schedule tasks based on priority, and find shortest paths using Dijkstra's algorithm.
A graph is a data structure consisting of a collection of vertices, also called nodes, connected by edges.
A tree is a special type of graph. Unlike trees, graphs can contain cycles, and vertices can have arbitrary connections with one another.
Edges can be directed or undirected, depending on whether the connections have a direction. They can also be weighted or unweighted, depending on whether each connection has an associated cost.
Here's an undirected graph with five vertices, A through E, and edges connecting A to B, A to C, B to D, C to D, and D to E.
There are two common ways to represent a graph.
The first is an adjacency list, where each vertex maintains a list of its neighbors. In our example, A maps to B and C, while D maps to B, C, and E.
This representation requires O(V + E) space, where V is the number of vertices and E is the number of edges.
The second is an adjacency matrix, a V by V grid where each cell contains 1 if an edge exists between the corresponding vertices, and 0 otherwise.
An adjacency matrix allows us to check whether an edge exists in O(1) time. However, it requires O(V²) space regardless of how many edges exist, and finding all neighbors of a vertex takes O(V) time.
Since most graphs we encounter in coding problems have far fewer than V² edges, an adjacency list is usually the better choice.
Graph problems often give us a list of edges, so our first step is usually to construct an adjacency list, which takes O(V + E) time. With an adjacency list backed by dynamic arrays, adding an edge takes amortized O(1) time.
There are two fundamental ways to traverse a graph.
Depth-first search, or DFS, explores as far as possible along one path before backtracking to explore other paths. It's typically implemented using recursion or a stack.
Breadth-first search, or BFS, explores the graph level by level, visiting closer vertices before those farther away. It's implemented using a queue.
Both algorithms use a visited set or array to avoid revisiting vertices and take O(V + E) time when using an adjacency list.
Use a graph whenever a problem involves relationships or connections, such as friendships in a social network, roads between cities, or courses with prerequisites.
Depending on the problem, we can use breadth-first search to find shortest paths in unweighted graphs, depth-first search to explore connected regions, topological sort to order dependencies in a directed acyclic graph, or Dijkstra's algorithm to find shortest paths in graphs with non-negative edge weights.
The final data structure is union find, also known as disjoint set union. It keeps track of elements organized into separate, non-overlapping groups and supports two main operations.
Loading simulation...
Find returns the root, or representative, of the group an element belongs to, while union merges the groups containing two elements. If two elements share the same root, they belong to the same group.
Union find is typically implemented using a parent array, where each element initially points to itself, forming its own independent group.
Let's start with six elements, numbered 0 through 5.
To merge 0 and 1, we set the parent of 1 to 0. Next, to merge 1 and 2, we find that the root of 1 is 0, so we set the parent of 2 to 0. We then merge 3 and 4 by setting the parent of 4 to 3.
We now have three separate groups. 0, 1, and 2 form the first group, 3 and 4 form the second, and 5 remains in its own group.
1 and 2 share the same root, 0, so they're connected. But 2 and 4 have different roots, meaning they belong to different groups.
Without optimization, these trees can grow into long chains, making find operations take O(n) time in the worst case. To avoid this, we use two important optimizations.
The first is path compression, which makes every node along the search path point directly to the root, speeding up future find operations.
The second is union by rank or size, which keeps the trees shallow by attaching the tree with a lower rank or smaller size beneath the other.
Together, these optimizations reduce the amortized time complexity of each operation to nearly constant time, formally O(α(n)), where α is a function that grows so slowly that its value stays at 4 or below for all practical input sizes.
Use union find when you need to dynamically maintain groups of elements and efficiently determine whether two elements are connected as new connections are added.
It's commonly used to count connected components, detect cycles in undirected graphs, and find minimum spanning trees using Kruskal's algorithm.
Whenever you encounter a new problem, start by identifying the operations you need to perform most frequently. Then, choose a data structure that makes those operations efficient.
Remember, you don't have to limit yourself to a single data structure. Many efficient solutions combine the strengths of multiple data structures, just like an LRU cache combines a hash map with a doubly linked list.
The key is to understand the strengths and trade-offs of each data structure so you can choose the right one for the problem at hand.