JavaScript Data Structures for Front-End Interviews
Introduction
Lesson 2 of chapter 9 compares JavaScript data structures for front-end interviews. Use Harbor Workshops examples to choose a structure based on the operations you need, such as lookup by id, maintaining order, or testing membership. Revisit the lesson on working with arrays and objects in JavaScript for array and object syntax. Data structures are part of the official Meta Coding Interview Preparation course. Course syllabus (opens in a new tab)
Learning objectives
By the end of this lesson you can:
- Describe arrays, objects,
Map, andSetand the cost of their common operations. - Choose between an array, an object, a
Map, and aSetfor a given need. - Implement and use stacks and queues with arrays and explain their order rules.
- Explain a linked list and when it differs from an array.
- Describe trees (including the DOM tree) and traverse them depth-first and breadth-first.
- Explain hash-based lookup and why it is fast on average.
- Use the frequency-counter, two-pointer, and normalization patterns.
- Normalize nested data into lookup tables, as you do in React state.
1. Arrays
An array stores items in order at numeric indexes. The cost estimates here assume ordinary dense arrays, fixed-cost comparisons, and constant work in callbacks. They describe a common implementation model.
| Operation | Typical cost | Note |
|---|---|---|
Read a[i] |
O(1) | Direct access |
push / pop (end) |
O(1) amortized for one item | Occasional resizing can make an individual operation cost more |
unshift / shift (start) |
O(n) in the straightforward model | Subsequent indexed positions change |
includes / indexOf |
O(n) | Scans |
splice in the middle |
O(n) | Items must move |
sort |
Engine-dependent | The language specifies ordering and stability. Analyze a chosen algorithm separately. |
map / filter / reduce |
O(n) | One pass, map and filter allocate a new array |
Use arrays when order matters and you mostly iterate or access by position: a list of sessions in display order, steps in a wizard.
const sessions = [
{ id: 's1', title: 'Pottery', seats: 4 },
{ id: 's2', title: 'Woodwork', seats: 0 },
{ id: 's3', title: 'Weaving', seats: 7 },
];
const open = sessions.filter((s) => s.seats > 0);
const titles = open.map((s) => s.title); // ['Pottery', 'Weaving']Looking up a session with find for each of m requests can take O(mn) for n sessions. It is quadratic when both sizes grow together. Consider building an index when lookups recur.
2. Objects, Map, and Set
Objects as dictionaries
A plain object uses string or symbol property keys. A dictionary can offer fast access by key in practice. The cost depends on the engine and object shape.
const byId = { s1: { title: 'Pottery' }, s2: { title: 'Woodwork' } };
byId['s1'].title; // 'Pottery'Non-symbol property keys are converted to strings. A normal object inherits names such as constructor, so use Object.hasOwn(byId, key) when checking for an own entry. Object.keys(byId).length counts its enumerable own string keys. For arbitrary ids, consider Map or a dictionary created with Object.create(null).
Map
A Map stores key/value pairs where keys can be any value, keeps insertion order, and has a size property.
const seatsLeft = new Map();
seatsLeft.set('s1', 4);
seatsLeft.set('s2', 0);
seatsLeft.get('s1'); // 4
seatsLeft.has('s9'); // false
seatsLeft.size; // 2In the usual hash-table model, reads are expected O(1) and inserts have expected amortized O(1) cost. ECMAScript requires average sublinear access and permits different implementations. Map is useful for arbitrary key types and for ids that could coincide with names inherited by a plain object.
Set
A Set stores unique values in insertion order. The hash-table model gives expected O(1) membership checks. Object values are unique by reference, so use a stable id when two distinct objects represent the same seat.
const selected = new Set(['s1']);
selected.add('s3');
selected.add('s1'); // no effect, already present
selected.has('s3'); // true
[...selected]; // ['s1', 's3']Use a Set for "have I seen this?", deduplication, and selected-item tracking.
Choosing
| Need | Best choice | Why |
|---|---|---|
| Ordered list to render | Array | Order and indexes |
| Look up a record by id | Object dictionary or Map |
Access by key without explicitly scanning the records |
| Unknown or non-string keys | Map |
Any key type, no prototype clash |
| Unique values, membership test | Set |
A membership operation and unique entries |
| Count occurrences | Map (frequency counter) |
Increment per key |
| Persist JSON-compatible state | Plain object or array | Default JSON.stringify does not include the entries of a Map or Set |
React can skip a state update when the next value is the same reference. Make a new set when the selection changes, for example setSelected(prev => prev.has(id) ? prev : new Set(prev).add(id)). Copying costs O(k) for k selected ids under the hash-table model. See React state and immutable updates.
3. Hashing in one paragraph
A hash table uses a hash of the key to choose where to look. Distinct keys can share a location, so the table resolves collisions. Expected constant-time lookup depends on distribution and table load. State that assumption when analyzing Map or Set. The standard permits other structures and does not require plain objects to use hashing. ECMAScript keyed collections (opens in a new tab)
4. The frequency counter and the lookup table
Frequency counter
Count occurrences with a Map, then answer questions from the counts.
function mostBooked(bookings) {
const counts = new Map();
for (const { workshopId } of bookings) {
counts.set(workshopId, (counts.get(workshopId) ?? 0) + 1);
}
let bestId = null;
let bestCount = 0;
for (const [id, count] of counts) {
if (count > bestCount) {
bestId = id;
bestCount = count;
}
}
return bestId;
}With the hash-table model, expected time is O(n + k) for n bookings and k distinct workshop ids. Working space is O(k). Ties keep the first workshop seen, and an empty list returns null.
The lookup table (index by id)
Problem: join each booking with its workshop. The slow way calls workshops.find for each booking: O(b × w). The fast way builds a table once.
function attachWorkshops(bookings, workshops) {
const byId = new Map(workshops.map((w) => [w.id, w])); // O(w)
return bookings.map((b) => ({ ...b, workshop: byId.get(b.workshopId) })); // O(b)
}Under the same model and fixed-size booking records, expected time is O(b + w). The lookup table uses O(w) working space and the output has b entries. This sample assumes unique workshop ids. A missing workshop gives an undefined value, so callers should decide how to present incomplete data.
5. Stacks and queues
A stack is last in, first out (LIFO). A queue is first in, first out (FIFO).
// Stack: use push and pop
const history = [];
history.push('/home');
history.push('/workshops');
history.pop(); // '/workshops' is the most recently pushed path
// Queue: use push and shift (shift is O(n) on a big array)
const jobs = [];
jobs.push('email-1');
jobs.push('email-2');
jobs.shift(); // 'email-1'Stacks appear in undo features, the call stack, and checking balanced brackets. Queues appear in task scheduling, breadth-first search, and message processing. Repeated shift calls can reindex many entries. A queue can advance a head index instead. Clear consumed entries and periodically compact the backing array if the queue is long-lived.
Worked example: balanced brackets
Problem. Given a string made of (, ), [, ], {, }, return true when every opener is closed by the right closer in the right order. Example: "{[()]}" is balanced, "([)]" is not.
Reasoning. The most recent unclosed opener must be closed first. "Most recent first" is a stack.
- For each character: if it is an opener, push it.
- If it is a closer, the stack must be non-empty and its top must be the matching opener; pop it. Otherwise return
false. - At the end the stack must be empty (no unclosed openers).
function isBalanced(text) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of text) {
if (ch === '(' || ch === '[' || ch === '{') {
stack.push(ch);
} else if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false;
}
}
return stack.length === 0;
}Trace "([)]": push (, push [; see ), pop gives [, which is not (, so return false. Trace "((": both pushed, stack not empty at the end, so false. Complexity: O(n) time, O(n) space for the stack.
Why other approaches are weaker. Counting each bracket type separately accepts "([)]" because the counts match even though the order is wrong. A stack is the structure whose rule (last in, first out) matches the nesting rule of the problem.
6. Linked lists
A linked list stores items in nodes; each node holds a value and a reference to the next node.
const list = {
value: 'Pottery',
next: { value: 'Woodwork', next: { value: 'Weaving', next: null } },
};| Operation | Array | Linked list |
|---|---|---|
| Access by index | O(1) | O(n) (walk from head) |
| Insert/remove at the start | O(n) | O(1) |
| Insert after a known node | O(n) | O(1) |
| Memory locality | Excellent | Poorer |
The linked-list insertion bounds assume you already hold the necessary node or predecessor. If you must locate it first, include the traversal cost. This reversal changes the links of a finite, acyclic list in place.
function reverseList(head) {
let previous = null;
let current = head;
while (current) {
const next = current.next; // remember the rest
current.next = previous; // flip the link
previous = current;
current = next;
}
return previous;
}O(n) time and O(1) space. The classic bug is losing the rest of the list by overwriting current.next before saving it.
7. Trees and the DOM
A tree is a hierarchy of nodes with one root, where each node has zero or more children. The DOM is a tree; so is a React component tree, a folder structure, and a nested comment thread.
const menu = {
label: 'Root',
children: [
{ label: 'Workshops', children: [{ label: 'Pottery', children: [] }] },
{ label: 'About', children: [] },
],
};Depth-first traversal (DFS)
Visit a node, then fully explore each child before the next. A recursive version is short:
function labels(node, out = []) {
out.push(node.label);
for (const child of node.children) labels(child, out);
return out;
}
labels(menu); // ['Root', 'Workshops', 'Pottery', 'About']Breadth-first traversal (BFS)
Visit level by level using a queue.
function levels(root) {
const result = [];
let queue = [root];
while (queue.length > 0) {
result.push(queue.map((n) => n.label));
queue = queue.flatMap((n) => n.children);
}
return result;
}
levels(menu); // [['Root'], ['Workshops', 'About'], ['Pottery']]Both visit n nodes in O(n) time for a well-formed tree. Excluding the returned O(n) labels, DFS keeps O(h) call frames for height h, and this BFS keeps O(w) frontier entries for maximum level width w.
Front-end application: finding the nearest ancestor
function closestWithClass(el, className) {
let node = el;
while (node) {
if (node.classList?.contains(className)) return node;
node = node.parentElement;
}
return null;
}For a simple class match, element.closest('.card') follows the same idea, starting at the element itself. The native method accepts CSS selectors. In delegated events, verify the target is an element and the matched ancestor belongs to the intended container. DOM Standard, closest (opens in a new tab)
8. Normalizing nested data
API responses are often nested. Storing them as-is in React state forces deep updates. Normalization stores each entity once in a lookup table and refers to others by id.
// Nested
const response = [
{ id: 'c1', name: 'Crafts', workshops: [{ id: 's1', title: 'Pottery' }] },
];
// Normalized
const state = {
categories: { c1: { id: 'c1', name: 'Crafts', workshopIds: ['s1'] } },
workshops: { s1: { id: 's1', title: 'Pottery' } },
};Update s1 in one lookup table and keep references to unchanged records where practical. Normalization reduces duplicate data. Rendering work still depends on which components read the state and whether their props or context values change.
9. Two pointers
Two indexes moving through the data often replace nested loops.
Problem. Given a sorted array of prices and a budget, find whether two distinct entries sum to exactly the budget. The amounts are safe integers and the pair sums fit in the safe integer range.
function hasPairWithSum(sortedPrices, target) {
let left = 0;
let right = sortedPrices.length - 1;
while (left < right) {
const sum = sortedPrices[left] + sortedPrices[right];
if (sum === target) return true;
if (sum < target) left++; // need a bigger sum
else right--; // need a smaller sum
}
return false;
}Input [5, 12, 20, 35, 50], target 55: 5+50=55, found immediately. Target 40: 5+50=55 too big, move right; 5+35=40, found. Time O(n), space O(1). Brute force is O(n²). A set-based version can process unsorted input in expected O(n) time under the hash-table model and uses O(n) space. Look up the complement before adding the current value so it takes two entries to make a pair. State both options and the assumption that decides between them.
10. Interview practice tips
Use the operation to guide the choice. Membership points to a Set, and counting or lookup by key points to a Map.
Compare the order in which elements leave. Nesting requires a stack, and processing in arrival order requires a queue.
Pitfalls:
- Using an array with
findinside a loop instead of building a lookup table. - Using an object as a map with user-controlled keys (
__proto__,constructor). - Expecting default JSON serialization to retain
MaporSetentries. Convert to arrays and rebuild the collection when restoring. - Mutating state structures in React and expecting a re-render.
- Using
shiftrepeatedly on a huge array and calling it O(1). - Writing a recursive tree traversal without a base case or on very deep input (stack overflow).
- Assuming sorted input when it was not stated.
11. Mini case study: group and rank the waiting list
Situation. Harbor Workshops stores waiting-list entries as { workshopId, email }. The same email might be added to the same workshop twice by double-clicking. Return the number of unique emails per workshop and the id of the longest list. For this exercise, workshop ids are strings and the demo treats trimmed, lowercase ASCII addresses as equal. A production system should use its established account identity and address rules.
Solution, commented.
- Structure choice. We need unique emails per workshop, so a
Mapfrom workshopId to aSetof emails. TheSetremoves duplicate clicks automatically. - Code.
function waitlistSummary(entries) {
const byWorkshop = new Map();
for (const { workshopId, email } of entries) {
if (!byWorkshop.has(workshopId)) byWorkshop.set(workshopId, new Set());
byWorkshop.get(workshopId).add(email.trim().toLowerCase());
}
const counts = Object.create(null);
let longest = null;
let longestSize = 0;
for (const [id, emails] of byWorkshop) {
counts[id] = emails.size;
if (emails.size > longestSize) {
longest = id;
longestSize = emails.size;
}
}
return { counts, longest };
}- Trace. Entries
s1/A@x.com,s1/a@x.com,s2/b@x.com: the first two normalize to the same email, sos1has size 1,s2has size 1;longestiss1because ties keep the first seen. State that tie rule aloud. - Complexity. Under the hash-table model and bounded id lengths, there are expected O(n) collection operations. Normalizing the emails also processes their characters. With L total email characters, use O(n + L) expected time when hashing and comparing keys takes linear time in their lengths. Working space includes the stored distinct email strings. The null-prototype result dictionary accepts ids such as
__proto__as ordinary keys. - Alternatives. An array scan for each email can use quadratic comparisons when many different addresses share a workshop. Sorting normalized records by workshop and email enables a linear scan after sorting. Include comparison cost and account for the first-seen tie rule if you choose that design.
Key terms
- Data structure: a way of organizing data for efficient operations.
- Hash table: a key-to-value structure using hashing for average O(1) lookup.
- Stack / queue: LIFO / FIFO collections.
- Linked list: nodes connected by references.
- Tree: a hierarchy with a root and children; the DOM is a tree.
- DFS / BFS: depth-first / breadth-first traversal.
- Normalization: storing entities once, referenced by id.
- Two pointers: moving two indexes to avoid a nested loop.
Summary checklist
- I know the cost of common array operations and avoid hidden O(n) calls in loops.
- I choose between array, object,
Map, andSetfor a stated need. - I build lookup tables instead of repeated
find. - I recognize stack and queue problems and implement them.
- I traverse trees depth-first and breadth-first.
- I apply the frequency-counter and two-pointer patterns.
- I keep React state immutable when using
SetorMap.
Sources
- Coding Interview Preparation (official course): https://www.coursera.org/learn/coding-interview-preparation (opens in a new tab)
- MDN Keyed collections (Map, Set): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections (opens in a new tab)
- DOM Standard, closest (opens in a new tab)
- MDN JSON.stringify (opens in a new tab)
- React useState (opens in a new tab)
