Data Structures and Algorithms for Frontend Interviews

Generally speaking, most frontend interviews tend to focus more on frontend-oriented coding questions, such as building UI components, managing state, or working with APIs. That said, many top companies will still test your understanding of core data structures and algorithms. It’s always a good idea to brush up on the fundamentals, just in case.
Honest Advice on Data Structures and Algorithms for Frontend
Now, let me be honest with you for a second. From my own experience, both as someone who has been interviewed for over 13 years and as someone who has conducted numerous interviews myself, if a company is strictly asking LeetCode-style algorithm questions for a frontend role, that’s a red flag. It suggests that the company likely lacks the necessary competency and resources to evaluate frontend engineers properly. Solving a linked list reversal or inverting a binary tree is not a strong indicator of whether someone can build a scalable UI, understand browser behavior, or write maintainable frontend code.
With that being said, I still think it’s essential to have a high-level understanding of the significant data structures, not because you’ll be asked to implement them from scratch, but because knowing them will help you recognize patterns and think through problems efficiently.
I would focus on a few core concepts: stacks, sets, queues, and priority queues; some basic tree traversal logic; ES6 maps; and hash tables. Occasionally, you may encounter a TRIE-style question that relates to a frontend concept (such as memoization or autocomplete). However, I’ve rarely been asked to reverse a linked list or build a graph using adjacency lists. And if I am? I walk away. Not worth it.
Now, if you do want to brush up on these concepts, the best free tutorials out there are from a nonprofit called FreeCodeCamp. We’re not affiliated with them at FrontendLead.com, but their videos are solid and beginner-friendly. Below, you’ll find a high-level summary of each concept, a simple example, and a direct link to the in-depth video for each topic.
Table of Contents
- Stacks
- Sets
- Queues & Priority Queues
- Binary Search Trees
- BST Traversals & Height
- Maps & ES6 Map
- Hash Tables
- Linked List
- Trie
- Heap (Max & Min)
- Graph & Adjacency Lists
- Graph BFS
1. Stacks (Built from Scratch)
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means the last item added is the first one removed — like a stack of plates. Stacks are used in scenarios like undo/redo functionality, browser history, and tracking function calls.
class Stack {
constructor() {
this.items = []; // Internal array to hold elements
}
push(value) {
// Add an element to the top of the stack
this.items[this.items.length] = value;
}
pop() {
// Return undefined if the stack is empty
if (this.items.length === 0) return undefined;
// Get the last item (top of stack)
const last = this.items[this.items.length - 1];
// Reduce the length of the array to remove it
this.items.length = this.items.length - 1;
// Return the removed value
return last;
}
peek() {
// Look at the top value without removing it
return this.items[this.items.length - 1];
}
isEmpty() {
// Return true if no elements are in the stack
return this.items.length === 0;
}
}
// Example usage
const stack = new Stack();
stack.push(10); // [10]
stack.push(20); // [10, 20]
stack.pop(); // 20
2. Sets (Built from Scratch)
A set is a collection of unique values — no duplicates allowed. You can use sets when you need to filter out duplicates, quickly check membership, or store flags. JavaScript includes a built-in Set object, but here’s how to build one from scratch.
class MySet {
constructor() {
this.items = {}; // Use an object to store unique values as keys
}
add(value) {
// Add the value as a key (won't allow duplicates)
this.items[value] = true;
}
has(value) {
// Return true if the key exists
return this.items.hasOwnProperty(value);
}
delete(value) {
// Remove the key from the object
delete this.items[value];
}
values() {
// Return an array of all stored keys
return Object.keys(this.items);
}
}
// Example usage
const set = new MySet();
set.add("apple");
set.add("apple"); // Duplicate won't be added
set.has("apple"); // true
set.delete("apple");
3. Queues (Built from Scratch)
A queue is a data structure that follows the First In, First Out (FIFO) principle. This means the first item added is the first one removed — like people waiting in line. Queues are useful for scheduling tasks, animations, or buffering streams.
class Queue {
constructor() {
this.items = {}; // Object to hold the queue
this.head = 0; // Index of the front element
this.tail = 0; // Index of the next empty slot
}
enqueue(value) {
// Add element at the tail index
this.items[this.tail] = value;
this.tail++;
}
dequeue() {
// If queue is empty, return undefined
if (this.head === this.tail) return undefined;
// Get the front item
const value = this.items[this.head];
// Remove it from the object
delete this.items[this.head];
this.head++;
// Return the dequeued value
return value;
}
peek() {
// Look at the front of the queue
return this.items[this.head];
}
isEmpty() {
// True if no elements left
return this.head === this.tail;
}
}
// Example usage
const queue = new Queue();
queue.enqueue("A");
queue.enqueue("B");
queue.dequeue(); // "A"
4. Binary Search Tree (Built from Scratch)
A Binary Search Tree (BST) is a hierarchical data structure where each node has up to two children. The left child contains values less than the parent, and the right child contains values greater than the parent. BSTs allow fast lookup, insertion, and deletion — typically in O(log n) time. They’re useful in search-heavy applications and form the foundation for other advanced data structures.
class TreeNode {
constructor(value) {
this.value = value; // The value stored in the node
this.left = null; // Left child
this.right = null; // Right child
}
}
class BinarySearchTree {
constructor() {
this.root = null; // Root of the tree
}
insert(value) {
const newNode = new TreeNode(value);
if (this.root === null) {
// If tree is empty, set the new node as root
this.root = newNode;
return;
}
let current = this.root;
while (true) {
if (value < current.value) {
// Go left
if (current.left === null) {
current.left = newNode;
return;
}
current = current.left;
} else {
// Go right
if (current.right === null) {
current.right = newNode;
return;
}
current = current.right;
}
}
}
find(value) {
let current = this.root;
while (current) {
if (value === current.value) return true;
current = value < current.value ? current.left : current.right;
}
return false;
}
}
// Example usage
const bst = new BinarySearchTree();
bst.insert(10);
bst.insert(5);
bst.insert(15);
bst.find(15); // true
bst.find(7); // false
5. BST Traversals & Height
Once you’ve built a tree, you’ll often want to traverse it — meaning visit each node in a specific order. The three main types of depth-first traversal are:
- In-order (left → root → right)
- Pre-order (root → left → right)
- Post-order (left → right → root)
Additionally, calculating the height of a tree is useful for understanding its depth or balance.
class TreeTraversal {
static inOrder(node, result = []) {
if (!node) return result;
TreeTraversal.inOrder(node.left, result); // Traverse left subtree
result.push(node.value); // Visit root
TreeTraversal.inOrder(node.right, result); // Traverse right subtree
return result;
}
static preOrder(node, result = []) {
if (!node) return result;
result.push(node.value); // Visit root
TreeTraversal.preOrder(node.left, result); // Traverse left
TreeTraversal.preOrder(node.right, result); // Traverse right
return result;
}
static postOrder(node, result = []) {
if (!node) return result;
TreeTraversal.postOrder(node.left, result); // Traverse left
TreeTraversal.postOrder(node.right, result); // Traverse right
result.push(node.value); // Visit root
return result;
}
static height(node) {
if (!node) return -1; // Height of empty tree is -1
const leftHeight = TreeTraversal.height(node.left);
const rightHeight = TreeTraversal.height(node.right);
return 1 + Math.max(leftHeight, rightHeight); // 1 + taller side
}
}
// Example usage
const exampleTree = new BinarySearchTree();
exampleTree.insert(10);
exampleTree.insert(5);
exampleTree.insert(15);
exampleTree.insert(2);
exampleTree.insert(7);
// Traversals
TreeTraversal.inOrder(exampleTree.root); // [2, 5, 7, 10, 15]
TreeTraversal.preOrder(exampleTree.root); // [10, 5, 2, 7, 15]
TreeTraversal.postOrder(exampleTree.root); // [2, 7, 5, 15, 10]
// Height
TreeTraversal.height(exampleTree.root); // 2
Watch the BST Traversal & Height video
6. Maps & ES6 Map (Built-in and Custom Example)
A Map is a key-value pair data structure, similar to an object — but unlike plain objects, ES6 Maps allow any type of key (including objects or functions), and they preserve insertion order. Maps are ideal when you need dynamic key-value storage without prototype pollution or when you need better performance than plain objects for frequent additions/deletions.
Using ES6 Map
// Create a new map
const map = new Map();
// Add key-value pairs
map.set("name", "FrontendLead");
map.set("visits", 5);
// Get a value by key
console.log(map.get("name")); // "FrontendLead"
// Check if a key exists
console.log(map.has("visits")); // true
// Delete a key
map.delete("visits");
// Iterate through keys and values
for (const [key, value] of map) {
console.log(key, value);
}
Building a Simple Map-like Object from Scratch
class SimpleMap {
constructor() {
this.store = {};
}
_hash(key) {
// Simple string-based hash (for demo only, not production-safe)
return typeof key + ":" + key.toString();
}
set(key, value) {
const hashedKey = this._hash(key);
this.store[hashedKey] = value;
}
get(key) {
const hashedKey = this._hash(key);
return this.store[hashedKey];
}
has(key) {
const hashedKey = this._hash(key);
return this.store.hasOwnProperty(hashedKey);
}
delete(key) {
const hashedKey = this._hash(key);
delete this.store[hashedKey];
}
entries() {
return Object.entries(this.store);
}
}
// Example usage
const myMap = new SimpleMap();
myMap.set("fruit", "banana");
myMap.set("count", 3);
myMap.get("fruit"); // "banana"
myMap.has("count"); // true
myMap.delete("fruit");
7. Hash Tables (Built from Scratch)
A Hash Table is a key-value data structure where keys are hashed to determine their index in an internal array. The strength of hash tables is that they offer near constant-time lookup, insert, and delete operations — making them ideal for caching, lookup tables, and duplicate detection. JavaScript’s `Object` and `Map` behave like hash tables, but let’s build one from scratch to really understand how it works.
class HashTable {
constructor(size = 53) {
this.buckets = new Array(size); // Fixed-size array of buckets
}
_hash(key) {
// Basic hash function for strings
let total = 0;
const PRIME = 31; // Prime helps reduce collisions
for (let i = 0; i < Math.min(key.length, 100); i++) { const char = key[i]; const value = char.charCodeAt(0) - 96; // 'a' -> 1
total = (total * PRIME + value) % this.buckets.length;
}
return total;
}
set(key, value) {
const index = this._hash(key);
if (!this.buckets[index]) {
this.buckets[index] = []; // Create a bucket if empty
}
// Check if key already exists, and update if so
for (let pair of this.buckets[index]) {
if (pair[0] === key) {
pair[1] = value;
return;
}
}
// Else, add new key-value pair
this.buckets[index].push([key, value]);
}
get(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
if (bucket) {
for (let [k, v] of bucket) {
if (k === key) return v;
}
}
return undefined;
}
has(key) {
return this.get(key) !== undefined;
}
delete(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
if (bucket) {
const filtered = bucket.filter(([k]) => k !== key);
this.buckets[index] = filtered;
}
}
keys() {
const keysArr = [];
for (let bucket of this.buckets) {
if (bucket) {
for (let [k] of bucket) {
keysArr.push(k);
}
}
}
return keysArr;
}
values() {
const valuesArr = [];
for (let bucket of this.buckets) {
if (bucket) {
for (let [, v] of bucket) {
valuesArr.push(v);
}
}
}
return valuesArr;
}
}
// Example usage
const table = new HashTable();
table.set("name", "Sarah");
table.set("age", 30);
table.set("city", "Tokyo");
table.get("age"); // 30
table.has("name"); // true
table.delete("city");
table.keys(); // ['name', 'age']
table.values(); // ['Sarah', 30]
8. Linked List (Built from Scratch)
A Linked List is a linear data structure where each element (called a node) contains a value and a pointer to the next node. Unlike arrays, linked lists don’t require contiguous memory, making insertions and deletions efficient (especially at the start or middle). They’re useful when working with dynamic data or implementing queues, stacks, and hash tables with collision chaining.
class ListNode {
constructor(value) {
this.value = value; // Value stored in the node
this.next = null; // Reference to the next node
}
}
class LinkedList {
constructor() {
this.head = null; // Start of the list
this.tail = null; // End of the list
this.length = 0;
}
append(value) {
const newNode = new ListNode(value);
if (!this.head) {
// If list is empty, set head and tail to new node
this.head = this.tail = newNode;
} else {
// Otherwise, link the new node at the end
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
}
prepend(value) {
const newNode = new ListNode(value);
newNode.next = this.head;
this.head = newNode;
if (!this.tail) {
this.tail = newNode;
}
this.length++;
}
find(value) {
let current = this.head;
while (current) {
if (current.value === value) return true;
current = current.next;
}
return false;
}
delete(value) {
if (!this.head) return;
// If the node to remove is the head
if (this.head.value === value) {
this.head = this.head.next;
this.length--;
return;
}
let current = this.head;
while (current.next && current.next.value !== value) {
current = current.next;
}
if (current.next) {
current.next = current.next.next;
this.length--;
if (!current.next) {
this.tail = current;
}
}
}
toArray() {
const result = [];
let current = this.head;
while (current) {
result.push(current.value);
current = current.next;
}
return result;
}
}
// Example usage
const list = new LinkedList();
list.append(10);
list.append(20);
list.prepend(5);
list.find(10); // true
list.delete(20);
list.toArray(); // [5, 10]
9. Trie (Prefix Tree, Built from Scratch)
A Trie (also called a prefix tree) is a special type of tree used to store strings. It’s particularly useful for tasks like autocomplete, dictionary word searches, or prefix matching. Each node represents a character and holds child nodes for branching. Tries offer efficient insert and lookup — especially when dealing with large vocabularies.
class TrieNode {
constructor() {
this.children = {}; // Maps each character to a TrieNode
this.isEndOfWord = false; // Marks end of valid word
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let current = this.root;
for (let char of word) {
if (!current.children[char]) {
current.children[char] = new TrieNode();
}
current = current.children[char];
}
current.isEndOfWord = true; // Mark the end of the word
}
search(word) {
let current = this.root;
for (let char of word) {
if (!current.children[char]) {
return false; // Character not found
}
current = current.children[char];
}
return current.isEndOfWord; // Return true only if it's a complete word
}
startsWith(prefix) {
let current = this.root;
for (let char of prefix) {
if (!current.children[char]) {
return false;
}
current = current.children[char];
}
return true; // If we got through the loop, the prefix exists
}
}
// Example usage
const trie = new Trie();
trie.insert("cat");
trie.insert("car");
trie.insert("cart");
trie.search("car"); // true
trie.search("care"); // false
trie.startsWith("ca"); // true
trie.startsWith("bat"); // false
10. Heap (Max and Min, Built from Scratch)
A Heap is a special kind of binary tree used to quickly access the largest (max-heap) or smallest (min-heap) element. It’s commonly used in priority queues, schedulers, and algorithms like Dijkstra’s shortest path. Heaps are typically implemented as arrays and use index math to find parent and child nodes.
MinHeap Implementation
class MinHeap {
constructor() {
this.heap = []; // Initialize an empty array
}
insert(value) {
this.heap.push(value); // Add value to the end
this._bubbleUp(); // Reorder heap to maintain structure
}
_bubbleUp() {
let index = this.heap.length - 1;
const element = this.heap[index];
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
let parent = this.heap[parentIndex];
if (element >= parent) break;
// Swap
this.heap[index] = parent;
this.heap[parentIndex] = element;
index = parentIndex;
}
}
extractMin() {
if (this.heap.length === 0) return undefined;
if (this.heap.length === 1) return this.heap.pop();
const min = this.heap[0];
this.heap[0] = this.heap.pop(); // Move last item to top
this._sinkDown(); // Restore heap property
return min;
}
_sinkDown() {
let index = 0;
const length = this.heap.length;
const element = this.heap[0];
while (true) {
let left = 2 * index + 1;
let right = 2 * index + 2;
let swap = null;
if (left < length && this.heap[left] < element) {
swap = left;
}
if (
right < length &&
this.heap[right] < (swap === null ? element : this.heap[left])
) {
swap = right;
}
if (swap === null) break;
this.heap[index] = this.heap[swap];
this.heap[swap] = element;
index = swap;
}
}
}
// Example usage
const minHeap = new MinHeap();
minHeap.insert(10);
minHeap.insert(5);
minHeap.insert(3);
minHeap.extractMin(); // 3
MaxHeap (Same as MinHeap, just reversed comparisons)
class MaxHeap {
constructor() {
this.heap = [];
}
insert(value) {
this.heap.push(value);
this._bubbleUp();
}
_bubbleUp() {
let index = this.heap.length - 1;
const element = this.heap[index];
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
let parent = this.heap[parentIndex];
if (element <= parent) break;
this.heap[index] = parent;
this.heap[parentIndex] = element;
index = parentIndex;
}
}
extractMax() {
if (this.heap.length === 0) return undefined;
if (this.heap.length === 1) return this.heap.pop();
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this._sinkDown();
return max;
}
_sinkDown() {
let index = 0;
const length = this.heap.length;
const element = this.heap[0];
while (true) {
let left = 2 * index + 1;
let right = 2 * index + 2;
let swap = null;
if (left < length && this.heap[left] > element) {
swap = left;
}
if (
right < length && this.heap[right] > (swap === null ? element : this.heap[left])
) {
swap = right;
}
if (swap === null) break;
this.heap[index] = this.heap[swap];
this.heap[swap] = element;
index = swap;
}
}
}
// Example usage
const maxHeap = new MaxHeap();
maxHeap.insert(10);
maxHeap.insert(20);
maxHeap.insert(5);
maxHeap.extractMax(); // 20
11. Graph & Adjacency List (Built from Scratch)
A Graph is a collection of nodes (also called vertices) connected by edges. Graphs can be directed or undirected, and weighted or unweighted. In frontend and general CS interviews, you’re most likely to encounter graphs via adjacency lists — a structure where each node points to a list of its neighbors. Graphs are used in navigation, social networks, recommendation engines, and more.
class Graph {
constructor() {
this.adjacencyList = {}; // Object to hold nodes and their edges
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
}
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1); // Undirected graph (for directed, remove this line)
}
removeEdge(v1, v2) {
this.adjacencyList[v1] = this.adjacencyList[v1].filter(n => n !== v2);
this.adjacencyList[v2] = this.adjacencyList[v2].filter(n => n !== v1);
}
removeVertex(vertex) {
while (this.adjacencyList[vertex].length) {
const adjacentVertex = this.adjacencyList[vertex].pop();
this.removeEdge(vertex, adjacentVertex);
}
delete this.adjacencyList[vertex];
}
print() {
console.log(this.adjacencyList);
}
}
// Example usage
const graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "C");
graph.print();
// Output:
// {
// A: ["B", "C"],
// B: ["A", "C"],
// C: ["A", "B"]
// }
Watch the Graph / Adjacency List video
12. Graph Traversal: Breadth-First Search (BFS) & Depth-First Search (DFS)
Once you’ve built a graph, the next step is traversing it. Two common methods are Breadth-First Search (BFS) and Depth-First Search (DFS).
- BFS: Explores neighbors level by level. It uses a queue and is great for finding the shortest path in unweighted graphs.
- DFS: Explores as far down a branch as possible before backtracking. It can be implemented recursively or with a stack.
Breadth-First Search (BFS)
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
bfs(start) {
const result = [];
const visited = {};
const queue = [start]; // Use queue for level-order traversal
visited[start] = true;
while (queue.length) {
const vertex = queue.shift();
result.push(vertex);
this.adjacencyList[vertex].forEach(neighbor => {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
});
}
return result;
}
}
// Example usage
const g = new Graph();
g.addVertex("A");
g.addVertex("B");
g.addVertex("C");
g.addVertex("D");
g.addVertex("E");
g.addEdge("A", "B");
g.addEdge("A", "C");
g.addEdge("B", "D");
g.addEdge("C", "E");
g.bfs("A"); // ["A", "B", "C", "D", "E"]
Depth-First Search (DFS – Recursive)
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
dfsRecursive(start) {
const result = [];
const visited = {};
const adjacencyList = this.adjacencyList;
function dfs(vertex) {
if (!vertex) return;
visited[vertex] = true;
result.push(vertex);
adjacencyList[vertex].forEach(neighbor => {
if (!visited[neighbor]) dfs(neighbor);
});
}
dfs(start);
return result;
}
}
// Example usage
const g2 = new Graph();
g2.addVertex("A");
g2.addVertex("B");
g2.addVertex("C");
g2.addVertex("D");
g2.addVertex("E");
g2.addEdge("A", "B");
g2.addEdge("A", "C");
g2.addEdge("B", "D");
g2.addEdge("C", "E");
g2.dfsRecursive("A"); // ["A", "B", "D", "C", "E"]
DFS (Iterative)
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
dfsIterative(start) {
const stack = [start];
const result = [];
const visited = {};
visited[start] = true;
while (stack.length) {
const vertex = stack.pop();
result.push(vertex);
this.adjacencyList[vertex].forEach(neighbor => {
if (!visited[neighbor]) {
visited[neighbor] = true;
stack.push(neighbor);
}
});
}
return result;
}
}
// Example usage
const g3 = new Graph();
g3.addVertex("A");
g3.addVertex("B");
g3.addVertex("C");
g3.addVertex("D");
g3.addEdge("A", "B");
g3.addEdge("A", "C");
g3.addEdge("B", "D");
g3.dfsIterative("A"); // ["A", "C", "B", "D"] or ["A", "B", "D", "C"]
Final Thoughts
While frontend interviews are rarely pure DSA marathons, the better you understand these concepts, the more confident and flexible you’ll be in solving problems, especially in companies that like to mix UI and logic.
For a deeper understanding, we highly recommend the full FreeCodeCamp Data Structures & Algorithms YouTube playlist.
