JavaScript Data Structures
Common Data Structures and Algorithms in JavaScript
Data structures organize data for efficient storage and access. Algorithms define the procedures used to process that data. JavaScript arrays, objects, classes, and built-in collections can implement many common structures, although understanding the underlying implementations helps explain their behavior and performance.
1. Stacks
A stack is a linear data structure in which elements are added and removed from the same end.
A stack follows LIFO behavior: “last in, first out.” The last element added is the first element removed.
Real-world examples
A stack of books:
The newest book is placed on top.
The top book must be removed before any book below it can be accessed.
A browser’s Back button:
Each visited page is placed on top of a stack.
Pressing Back removes the most recently visited page and reveals the previous page.
Common stack operations
Push: Adds an element to the top of the stack.
Pop: Removes and returns the top element.
Peek: Returns the top element without removing it.
Size or length: Reports the number of elements in the stack.
Using an array as a stack
A JavaScript array already provides the operations needed for a stack:
pushadds an item to the end.popremoves and returns the last item.The final array element represents the top of the stack.
The array’s
lengthgives the stack size.
Using a stack to detect palindromes
A palindrome is a word that reads the same forward and backward.
Examples include:
bobracecar
The stack-based process is:
Create an empty stack.
Push every character of the word onto the stack in forward order.
Pop each character from the stack.
Concatenate the popped characters to form the reverse of the original word.
Compare the original word with the reversed word.
Because a stack returns characters in reverse insertion order, the resulting string is the reverse of the original.
If the original word and reversed word are equal, the word is a palindrome; otherwise, it is not.
Implementing a stack with a class
A manually implemented stack can use:
A storage object containing the elements.
A counter tracking the number of elements.
The counter also identifies the next available position.
Push operation
To push a value:
Store the value at the position represented by the current count.
Increase the count by one.
Pop operation
To pop a value:
If the count is zero, return
undefinedbecause the stack is empty.Decrease the count by one.
Retrieve the item at the new count position.
Delete the item from storage.
Return the retrieved item.
Peek operation
To peek:
Check the position at
count - 1.Return its value without deleting it.
The subtraction is necessary because the count points to the next unused position, not the final stored element.
Size operation
The size is the current count.
Stack behavior example
If a stack receives the values 1 and 2:
Push 1.
Push 2.
Peek returns 2.
Pop returns and removes 2.
Peek now returns 1.
The key difference is that pop changes the stack, whereas peek only examines it.
2. Sets
A set is a collection of values in which each value appears at most once. Sets generally do not depend on element order.
The main purpose of a set is often to determine whether a value is present.
Set properties
Duplicate values are not allowed.
Values are not normally treated as being in a meaningful order.
Membership testing is a central operation.
Basic set operations
A custom set can provide the following methods.
Has
The has operation checks whether an element exists.
For an array-based implementation, it can use an index search:
A result other than −1 means the element is present.
A result of −1 means the element is absent.
Values
The values operation returns all values in the set.
Add
To add an element:
Check whether the element is already present.
If it is absent, add it to the collection.
Return
trueif it was added.Return
falseif it was already present.
This prevents duplicates.
Remove
To remove an element:
Check whether it exists.
Find its index.
Remove one element at that index.
Return
trueif removal occurred.Return
falseif the element was absent.
Size
The size is the number of stored elements.
JavaScript’s built-in Set
ECMAScript 2015 introduced the built-in Set object. Its corresponding operations include:
hasvaluesadddeletesize
Important differences include:
The built-in operation is called
delete, notremove.sizeis a property, not a method, so it is accessed without parentheses.valuesreturns an iterator rather than an ordinary array.addreturns the set itself, not a Boolean indicating whether a new item was added.
Set union
The union of two sets contains every value appearing in either set, with duplicates removed.
For sets A and B:
A typical implementation:
Create an empty result set.
Add every value from the first set.
Add every value from the second set.
Rely on the set’s duplicate-prevention behavior.
Set intersection
The intersection contains only values present in both sets.
For sets A and B:
A typical implementation:
Create an empty result set.
Examine each value in the first set.
Add it if the second set contains it.
Set difference
The difference contains values that belong to one set but not the other.
For the difference of A relative to B:
A typical implementation:
Examine every value in the first set.
Add the value if the second set does not contain it.
Subsets
A set A is a subset of set B if every element of A also belongs to B.
To test this:
Examine every element of the first set.
Confirm that the second set contains each one.
Return
trueonly if every element passes the test.
For example, if set A contains only a and set B contains a, b, and d, then A is a subset of B.
3. Queues
A queue is a linear data structure in which elements enter at one end and leave from the other.
A queue follows FIFO behavior: “first in, first out.” The first element added is the first element removed.
Real-world examples
A line of customers:
The first person to enter the line is served first.
A print queue:
Documents are printed in the order they were submitted.
Queue operations
Enqueue: Adds an element to the back.
Dequeue: Removes and returns the element at the front.
Front: Returns the front element without removing it.
Size: Returns the number of queued items.
Is empty: Checks whether the queue contains no items.
Array-based queue
One implementation adds items to the end of an array and removes them from the beginning.
Enqueue uses
push.Dequeue uses
shift.The front item is at index 0.
The size is the array length.
If the queue receives a, b, and c, its order is:
abc
After one dequeue, a is removed, leaving b at the front.
Priority queues
A priority queue associates each element with a priority.
If all priorities are equal, the structure behaves like an ordinary FIFO queue. When priorities differ, higher-priority elements move ahead of lower-priority elements.
For example:
Priority 5 items are placed before priority 4 items.
Items with the same priority remain in the order in which they were added.
Enqueuing into a priority queue
To insert an element:
If the queue is empty, add the element directly.
Otherwise, compare its priority with existing elements.
Insert it before the first item with a lower priority.
If no such item is found, append it to the end.
The implementation uses an insertion operation such as array splicing to place the item in the correct position.
A priority queue’s dequeue operation removes the first item. Depending on the design, it may return:
The entire element-priority pair.
Only the element itself.
4. Trees and Binary Search Trees
A tree is a hierarchical data structure made of connected nodes.
Tree terminology
Node: A data element in the tree.
Root: The top node.
Parent: A node with one or more children.
Child: A node connected below a parent.
Leaf: A node with no children.
Subtree: A node together with all of its descendants.
A child can also be the parent of its own subtree.
Binary trees
A binary tree allows each node to have at most two children:
A left child.
A right child.
A general tree can have any number of children, whereas a binary tree has no more than two per node.
Binary search trees
A binary search tree, or BST, is an ordered binary tree.
For each node:
Values in the left subtree are less than or equal to the node’s value.
Values in the right subtree are greater than or equal to the node’s value.
This ordering makes searching more efficient because each comparison can eliminate approximately half of the remaining tree on average.
Average-case operations can take time proportional to:
where n is the number of stored nodes.
This is generally better than searching an unsorted array, which may require linear time:
A hash table is generally faster on average for direct key lookup, often providing O(1) average lookup time.
Representing a BST
A node contains:
data: The stored value.left: A reference to the left child.right: A reference to the right child.
The tree itself contains a root reference. The root is initially null when the tree is empty.
Adding a node
To add a value:
Create a new node.
If the tree is empty, make it the root.
Otherwise, compare the new value with the current node.
If it is smaller, move left.
If it is larger, move right.
Continue until an empty child position is found.
Place the new node in that position.
If the value equals an existing value, the implementation may reject it rather than create a duplicate.
The search for an insertion position can be implemented recursively. Each recursive call examines a smaller subtree.
Finding the minimum
The minimum value in a BST is the leftmost value.
Process:
Start at the root.
Follow left-child references while they exist.
Return the data in the final node.
Finding the maximum
The maximum value is the rightmost value.
Process:
Start at the root.
Follow right-child references while they exist.
Return the data in the final node.
Searching for a value
To determine whether a value exists:
Start at the root.
If the current node is
null, the value is absent.If the target equals the current node’s data, return
true.If the target is smaller, continue with the left child.
If the target is larger, continue with the right child.
If the search reaches
null, returnfalse.
Removing a node
Removing a BST node has three cases.
Case 1: The node is a leaf
A leaf has no children.
Replace the node with
null.The parent no longer points to it.
Case 2: The node has one child
If the node has only a right child:
Replace the node with its right child.
If the node has only a left child:
Replace the node with its left child.
This allows the child subtree to remain connected to the parent.
Case 3: The node has two children
A node with two children cannot simply be replaced by either child without potentially violating the BST ordering.
A common solution is:
Move to the node’s right subtree.
Find the leftmost node in that subtree.
This node is the smallest value greater than the node being removed.
Copy its data into the node being removed.
Recursively remove the duplicate node from the right subtree.
This replacement preserves the BST ordering.
5. Tree Height and Traversal
Tree height
The height of a node is its distance from the root, measured in edges or levels according to the convention being used.
In the source implementation:
The root has height 0.
Its children have height 1.
The next level has height 2.
A tree can have different path lengths from the root to its leaves.
Minimum and maximum height
Minimum height: Distance from the root to the nearest leaf or first node without two children.
Maximum height: Distance from the root to the deepest leaf.
A tree is considered balanced in this context when the minimum and maximum heights differ by no more than one:
Equivalently, their difference is at most one.
Balanced trees are more efficient for searching because their height remains close to logarithmic rather than becoming strongly linear.
Recursive height calculation
For each node:
Recursively calculate the height of the left subtree.
Recursively calculate the height of the right subtree.
Select the smaller value for minimum height or the larger value for maximum height.
Add one for the current level.
An empty subtree can return a base height of −1, allowing the root of a one-node tree to have height 0.
Depth-first traversal
Depth-first search explores one branch as deeply as possible before moving to another branch.
The three main depth-first traversals differ in when they process the current node.
In-order traversal
The order is:
Traverse the left subtree.
Process the current node.
Traverse the right subtree.
For a BST, in-order traversal produces values in sorted order from least to greatest.
Example pattern:
Pre-order traversal
The order is:
Process the current node.
Traverse the left subtree.
Traverse the right subtree.
Example pattern:
Pre-order traversal visits parent nodes before their descendants.
Post-order traversal
The order is:
Traverse the left subtree.
Traverse the right subtree.
Process the current node.
Example pattern:
Post-order traversal visits child nodes before their parents.
Level-order traversal
Level-order traversal is a breadth-first search of a tree.
It visits:
The root.
All nodes at the next level.
All nodes at the following level.
Continue until every level has been processed.
A queue is used:
Add the root to the queue.
Remove the first node.
Add its value to the result.
Enqueue its non-null children.
Repeat until the queue is empty.
This produces an order such as:
6. Hash Tables
A hash table stores key-value pairs and uses a hash function to locate values efficiently.
Hash tables commonly implement maps and object-like collections.
Hash table performance
The average time complexity of hash table operations is:
Search: O(1)
Insert: O(1)
Delete: O(1)
These are average values. Poor hashing or many collisions can make operations slower.
Hash functions
A hash function converts a key, often a string, into a numerical index.
A hash function should:
Be consistent: the same key always produces the same result.
Distribute keys across the available buckets.
Produce an index within the storage range.
A simple example can:
Start with a hash value of zero.
Visit each character in the key.
Add the character code to the hash.
Use the remainder after division by the number of buckets.
The index can be calculated as:
For five buckets, possible indexes are 0, 1, 2, 3, and 4.
Collisions
A collision occurs when different keys produce the same index.
For example, two names may both hash to index 2.
A common collision-handling technique is to store multiple key-value pairs in the same bucket. When looking up a key, the bucket is searched until the matching key is found.
Adding values
To add a key-value pair:
Hash the key to find its bucket.
If the bucket is empty, create a bucket containing the pair.
If the bucket already contains entries, search for the key.
If the key exists, update its value.
If the key does not exist, add a new pair to the bucket.
Removing values
To remove a key:
Hash the key to locate its bucket.
If the bucket contains only one matching entry, delete the bucket entry.
If multiple entries exist, search the bucket.
Remove only the pair with the matching key.
Looking up values
To retrieve a value:
Hash the key.
Locate the corresponding bucket.
If no bucket exists, return
undefined.Search the bucket for the matching key.
Return its associated value.
JavaScript objects and built-in map-like structures usually hide these implementation details, but the underlying principle remains key hashing followed by bucket lookup.
7. Linked Lists
A linked list stores elements in nodes. Each node contains:
The stored element.
A reference to the next node.
A typical node has the form:
element: The data.next: A pointer to the next node ornull.
Linked-list structure
A linked list maintains:
A head, which points to the first node.
A length, which records the number of nodes.
The final node’s next reference is null.
Linked lists compared with arrays
Linked-list advantages
Dynamic size.
Efficient insertion and deletion when the correct position is known.
No need to allocate extra unused capacity.
Linked-list disadvantages
No direct random access.
Finding an element at index i requires traversing preceding nodes.
Sequential access is slower than array indexing.
Array advantages
Immediate access by index.
Efficient sequential traversal.
Simple built-in operations.
Array disadvantages
Insertions and deletions in the middle may require shifting elements.
Arrays may allocate more capacity than currently needed.
Fixed-size behavior exists at a lower implementation level, even though JavaScript arrays resize automatically.
Adding to the end
To add an element at the end:
Create a new node.
If the list is empty, make the new node the head.
Otherwise, start at the head.
Follow
nextreferences until reaching the final node.Set the final node’s
nextto the new node.Increase the length.
Removing an element by value
To remove a node containing a particular element:
Start at the head.
If the head contains the target, move the head to the head’s next node.
Otherwise, track both:
The current node.
The previous node.
Continue until the target is found.
Set the previous node’s
nextto the current node’snext.This skips the current node and removes it from the chain.
Decrease the length.
Checking whether the list is empty
The list is empty when:
Finding an element’s index
To find the index of an element:
Start at the head.
Initialize the index to 0.
Compare the current node’s element with the target.
If they match, return the current index.
Move to the next node and increase the index.
If the end is reached, return −1.
Finding an element by index
To retrieve the element at a given index:
Start at the head.
Initialize a counter to 0.
Move through the list until the counter equals the requested index.
Return the current node’s element.
Adding at a specific index
To insert at an index:
Create a new node.
Reject invalid indexes.
If the index is 0, point the new node to the current head and make it the new head.
Otherwise, traverse until reaching the insertion position.
Set the new node’s
nextto the current node.Set the previous node’s
nextto the new node.Increase the length.
Removing at a specific index
To remove at an index:
Reject negative indexes and indexes beyond the list.
If the index is 0, move the head to the next node.
Otherwise, traverse to the target position while tracking the previous node.
Set the previous node’s
nextto the target node’snext.Decrease the length.
Return the removed node.
8. Tries
A trie, also called a prefix tree, is a tree designed to store associative data, especially strings.
Each node in a trie represents one character or one step in a word.
Trie structure
Each node contains:
A collection of child keys.
References to child nodes.
An
isEndindicator showing whether the node completes a word.
A trie can store words with shared prefixes efficiently.
For example, ball and bat share the prefix ba. The trie stores that shared prefix once, then branches when the words diverge.
Word endings
A word can end at a node even if that node has children.
For example, a trie may contain both:
dodoll
The node representing o is marked as the end of do, while also having a child leading toward doll.
Adding a word
To add a word recursively:
Begin at the root.
Examine the first character.
If the corresponding child does not exist, create it.
Move to that child.
Remove the first character from the remaining input.
Repeat recursively.
When no characters remain, mark the current node as an ending node.
If a shared prefix already exists, the existing nodes are reused.
Checking whether a word exists
To determine whether a word is stored:
Start at the root.
Examine the first character.
If no matching child exists, return
false.Move to the matching child.
Continue with the remaining characters.
After the final character, check the node’s ending marker.
Return
trueonly if the final node marks the end of a complete word.
This distinction prevents a prefix from being incorrectly treated as a complete word. For example, dor should not be considered present merely because a longer word such as dorm exists.
Listing all words
To list every word:
Start at the root.
Maintain a string containing the characters accumulated along the current path.
Recursively visit every child.
Append each child’s character to the current string.
Whenever an ending node is reached, add the current string to the results.
Backtrack and explore other branches.
Tries are useful for dictionaries, autocomplete, prefix searches, and word validation.
9. Binary Heaps
A binary heap is a partially ordered binary tree that satisfies the heap property.
Heap properties
Each node has at most two children. The relationship between parent and child depends on the heap type.
Min-heaps
In a min-heap, every parent is less than or equal to its children.
The smallest value is always at the root.
Max-heaps
In a max-heap, every parent is greater than or equal to its children.
The largest value is always at the root.
The relative order of sibling nodes does not matter as long as the heap property is preserved.
Complete binary trees
A heap is also a complete binary tree:
Every level is completely filled except possibly the last.
The final level is filled from left to right.
Array representation
Heaps are commonly stored in arrays instead of node objects.
Index 0 is often left unused so that child-parent calculations are simple. For a node at index i:
Left child:
Right child:
Parent:
The final array index corresponds to the heap size when index 0 is reserved.
Inserting into a min-heap
To insert a value:
Add it to the end of the array.
Compare it with its parent.
If it is smaller than the parent, swap them.
Continue moving upward until:
The value reaches the root.
The parent is smaller or equal.
This process is called bubbling up or percolating up.
Adding a value at the end preserves the complete-tree structure before reordering.
Removing from a min-heap
Removal always removes the smallest value at the root.
Process:
Save the root value.
Move the final array element to the root.
Remove the final array position.
Compare the new root with its children.
Swap it with the smaller child if necessary.
Continue moving it downward until the heap property is restored.
Return the original root value.
This process is called bubbling down or percolating down.
If the node has two children, it must be swapped with the smaller child in a min-heap. Otherwise, choosing the larger child could leave the node greater than the other child.
Heap sort
Heap sort uses a heap to sort an array.
Process:
Create a min-heap.
Insert every item from the unsorted array.
Repeatedly remove the smallest heap item.
Append each removed item to a result array.
Continue until the heap is empty.
The result is ordered from least to greatest.
Heap sort has average- and worst-case time complexity:
10. Graphs
A graph is a collection of nodes and the relationships connecting them.
Graph terminology
Node or vertex: An item in the graph.
Edge: A connection between two nodes.
Neighbor: A node directly connected to another node.
Examples
A social network can be represented as:
Nodes: People.
Edges: Friendships.
A web graph can be represented as:
Nodes: Web pages.
Directed edges: Links from one page to another.
Undirected graphs
An undirected graph has edges with no direction.
If node A is connected to node B, the connection can generally be traveled in either direction.
Friendship networks are often modeled this way.
Directed graphs
A directed graph has edges with a direction.
An edge from A to B does not necessarily mean that an edge from B to A exists.
Web-page links are an example because one page may link to another without the reverse link.
Weighted graphs
A graph can be:
Unweighted: An edge is represented simply by whether it exists.
Weighted: Each edge has a numerical value representing cost, distance, time, or another quantity.
Adjacency lists
An adjacency list associates each node with its neighboring nodes.
For example:
Node A lists B.
Node B lists A and C.
Node C lists B.
Adjacency lists are efficient when each node has relatively few neighbors. They can be represented using objects, maps, arrays, or numeric indexes.
Adjacency matrices
An adjacency matrix is a two-dimensional array.
Rows represent source nodes.
Columns represent destination nodes.
A 1 indicates an edge.
A 0 indicates no edge.
For n nodes, the matrix has dimensions:
In a directed graph, the entry at row i and column j indicates whether an edge leads from node i to node j.
The matrix must contain the same number of entries in every row.
Incidence matrices
An incidence matrix also uses a two-dimensional array, but its rows and columns represent different things:
Rows represent nodes.
Columns represent edges.
Each column corresponds to one unique edge. For an undirected edge connecting two nodes, the column contains a 1 in the rows for both connected nodes.
For directed graphs:
A 1 represents an edge leaving a node.
A negative 1 represents an edge entering a node.
Unlike an adjacency matrix, an incidence matrix does not need to be square because the number of nodes and edges can differ.
11. Graph Traversal and Breadth-First Search
Graph traversal refers to visiting nodes in a graph according to a systematic procedure.
The two major traversal strategies are:
Breadth-first search.
Depth-first search.
Breadth-first search
Breadth-first search, or BFS, visits nodes in layers.
Starting from a root node, it:
Visits all directly connected neighbors.
Visits the neighbors of those nodes.
Continues outward one edge at a time.
BFS is useful for finding the shortest number of edges between a starting node and other reachable nodes in an unweighted graph.
Distance representation
A distance object or array stores each node’s distance from the root.
Initially:
Every distance is set to infinity.
The root’s distance is set to 0.
Infinity indicates that a node has not yet been reached. If the algorithm finishes and a node still has distance infinity, that node is unreachable from the root.
BFS using an adjacency matrix
Given an adjacency matrix and a root index:
Create a distance array filled with infinity.
Set the root distance to 0.
Create a queue and add the root.
While the queue is not empty:
Remove the first node.
Examine its row in the adjacency matrix.
Find every connected neighbor.
If a neighbor’s distance is still infinity:
Set its distance to the current node’s distance plus one.
Add the neighbor to the queue.
Return the distance array.
Finding neighbors in a matrix
For a current node, its row contains:
1 at indexes of connected nodes.
0 at indexes of unconnected nodes.
The algorithm searches for each 1 in the row. After finding one neighbor, it continues searching from the next index to find additional neighbors.
Why distances are assigned only once
A node’s first discovery in BFS gives its shortest distance from the root because BFS explores nodes in increasing distance order.
If a node’s distance is no longer infinity, it has already been reached by the shortest known route. It does not need to be added to the queue again.
Example of BFS distances
Suppose the root is node 1:
Node 1 has distance 0.
A directly connected node has distance 1.
A node reached through one intermediate node has distance 2.
A node requiring three edges has distance 3.
An unreachable node remains at infinity.
The resulting distance array describes how many edges must be traversed from the root to reach each node.

Ask anything
We've read this whole study set, so questions about it get the best answers.