JavaScript Data Structures


JavaScript Data Structures

Corey
Welcome back. Today we're working through common data structures and algorithms in JavaScript: stacks, sets, queues, trees, hash tables, linked lists, tries, heaps, and graphs. We'll focus on what each structure represents, when it is useful, and the key implementation ideas.

Maria
Let's begin with the stack. Picture a stack of books: the last book placed on top is the first one removed. That's called last in, first out, or LIFO.

Corey
A browser's Back button is another example. When you visit Facebook after Twitter, Facebook is pushed onto the top of the visited-sites stack. Pressing Back pops Facebook off, leaving Twitter at the top. The traditional stack operations are push to add an item, pop to remove and return the top item, peek to view the top without removing it, and size or length to count the items.

Maria
And JavaScript arrays already provide what we need for a stack. We can use push and pop directly, which is why a separate stack class is often unnecessary.

Corey
A useful example is checking for a palindrome. We put every character of a word, such as racecar, into an array stack from left to right. Then we pop the characters off one at a time and build a reversed string. If the reversed string equals the original using strict equality, the word is a palindrome; otherwise it is not.

Maria
The custom Stack implementation makes the same behavior explicit. It keeps an object called storage and a count of how many items are present. Push stores the value at the current count and increments count; pop returns undefined if the stack is empty, otherwise it decrements count, retrieves the final value, deletes it, and returns it.

Corey
The other methods are straightforward: size returns count, while peek returns storage at count minus one without deleting it. So if we push 1 and then 2, peek gives 2, pop gives 2 and removes it, and another peek gives 1. The stack can hold different kinds of values, including strings.

Maria
A set is different from a stack because its main rule is uniqueness. A set is like an array without duplicate items, and its values have no particular order. Its common purpose is simply checking whether an item is present.

Corey
In the custom MySet implementation, the collection is stored in an array. Has uses indexOf and returns true when the result is not negative one. Values returns the collection. Add first checks has; if the element is absent, it pushes it and returns true, otherwise it returns false.

Maria
Remove checks whether the item exists, finds its index, and uses splice to remove one element. It returns true if removal happened and false otherwise. Size returns the collection length.

Corey
The implementation also demonstrates operations involving two sets. Union combines both sets while removing duplicates. Intersection creates a new set containing only values present in both. Difference contains values in the first set but not the other. Subset returns true when every value in the first set is also in the second.

Maria
JavaScript's ES6 Set provides values, add, delete, and size, although delete is the built-in name instead of remove, and size is a property rather than a method. Its values method returns an iterator rather than the array used by the custom version. Also, ES6 add returns the set itself, not a Boolean indicating whether a new value was inserted.

Corey
Now compare a queue with a stack. A queue is first in, first out, or FIFO, like people waiting in a store line. A print queue works the same way: documents are printed in the order they were sent.

Maria
The array-based queue stores new items at the end with push and removes the oldest item from the beginning with shift. Enqueue adds an item, dequeue removes and returns the front item, front views the first item without removing it, size returns collection.length, and isEmpty checks whether the length is zero.

Corey
A priority queue adds a priority to each item. If priorities are equal, the queue behaves normally and preserves insertion order. But an item with a higher priority is placed ahead of items with lower priority. In the example, items with priority 5 come before items with priority 4, while two items with the same priority remain in the order they were added.

Maria
The priority enqueue operation scans the existing collection. When it finds an item with a lower priority, it inserts the new item before it using splice. If no such position is found, it pushes the item at the end. Dequeue can return either the complete item-priority pair or just the item, depending on the implementation.

Corey
A tree organizes data hierarchically. Its data points are nodes; the top node is the root. Nodes that lead to other nodes are parents, the connected nodes below them are children, and nodes with no children are leaves. Every node can also be viewed as the parent of its own subtree.

Maria
The focus here is a binary search tree, or BST. A binary tree allows at most two children per node. In a binary search tree, values in the left subtree are less than or equal to the parent, and values in the right subtree are greater than or equal to it. That ordering allows search, insertion, and deletion to skip roughly half the tree on average, giving logarithmic behavior, which is better than searching an unsorted array but slower than the corresponding hash-table operations.

Corey
The JavaScript implementation uses a Node class containing data, left, and right references, plus a BinarySearchTree class whose root begins as null. To add a value, the first value becomes the root. Later values are compared with the current node: smaller values go left, larger values go right, and equal values are not added.

Maria
The placement process is recursive. If the desired child position is null, the new node is attached there. Otherwise, the same search is called on that child, continuing down the tree. For example, adding 23 to a tree containing 50 and 17 first moves left from 50, then right from 17, where 23 can be attached.

Corey
Finding the minimum and maximum takes advantage of the ordering. Starting at the root, keep moving left until there is no left child to find the minimum. Keep moving right to find the maximum. The find operation returns true if the target matches the current node, otherwise it continues left or right according to the comparison, eventually returning false if it reaches null.

Maria
Removal has three cases. A node with no children is replaced with null. A node with one child is replaced by that child. A node with two children is replaced by the smallest node in its right subtree: move right once, then keep moving left. The recursive removal process reconnects the affected subtree correctly.

Corey
Tree height is the distance from the root to a node level: the root has height zero, the next level has height one, and so on. Minimum height reaches the first leaf, while maximum height reaches the deepest leaf. A tree is considered balanced here when the minimum and maximum heights differ by at most one, which makes searching more efficient.

Maria
Tree traversal visits every node in a particular order. In-order traversal explores the left subtree, then the node, then the right subtree, so a BST produces sorted values. Pre-order visits the node before its child subtrees. Post-order visits the child subtrees before the node.

Corey
Those three are depth-first traversals because they explore a subtree deeply before moving to another. Level-order traversal is breadth-first: it uses a queue, starts with the root, removes one node at a time, adds its value to the result, and enqueues its non-null children. That produces values level by level.

Maria
A hash table stores key-value pairs through a hash function. The function converts a key, often a string, into a number that serves as an array index. A good hash function is consistent, so the same key always produces the same index, and it tries to distribute different keys across different buckets.

Corey
When two keys produce the same index, we have a collision. One solution is to store multiple key-value pairs in that bucket and search through them during lookup. The average time for search, insertion, and deletion in a hash table is O of 1, so it is generally faster for these operations than a tree or an unsorted array.

Maria
The example hash function starts at zero, adds the character code of each character, and returns the hash modulo the storage limit. With five buckets, the remainder is always from zero through four. The table's add operation computes the bucket, updates an existing key if found, or adds a new pair to the bucket if not.

Corey
Lookup hashes the key again and searches its bucket for the matching key. Removal deletes the entire bucket entry when it contains only that key, or removes just the matching pair when the bucket contains a collision. JavaScript objects commonly provide hash-table behavior, so developers usually do not need to build one manually.

Maria
A linked list stores elements in nodes. Each node contains the element and a reference to the next node. The list has a head pointing to the first node and a size. The final node's next reference is null.

Corey
Compared with arrays, linked lists have dynamic size and efficient insertion and deletion once the relevant position is found. Arrays provide fast random access, such as immediately retrieving index five, while a linked list must follow each reference from the head to reach index five. Arrays can also waste memory when allocated larger than necessary, whereas linked lists grow as nodes are added.

Maria
To add at the end, create a node, use it as the head if the list is empty, or walk from the head until the current node's next is null, then connect the new node there. To remove an element, keep both the current and previous nodes. If the head contains the target, move the head forward; otherwise, change the previous node's next reference so it skips the target node.

Corey
The linked list also supports size, head, and isEmpty operations, plus indexOf and elementAt. IndexOf walks through the nodes while tracking an index, returning negative one if the element is absent. ElementAt walks until the requested index and returns that node's element. AddAt inserts a new node at a chosen position, while removeAt reconnects the surrounding nodes and decreases the length.

Maria
A trie, sometimes called a prefix tree, is a specialized tree for associative data such as words. Each node represents a letter, and branches share common prefixes. For example, ball and bat share the path for ba, then branch at their next letters.

Corey
Each trie node has a map of letter keys, a collection of possible next letters, and an end marker indicating whether a complete word ends there. That marker matters because a sequence can be a prefix without being a word: the path for door may exist while the final r is not marked as the end of a stored word.

Maria
Adding a word is recursive. At each step, check whether the current node already has the next letter; create a node if necessary, then continue with the remaining substring. Once the input is empty, mark the current node as an ending node.

Corey
Checking a word follows one letter at a time from the root. If a needed letter is missing, return false immediately. After all letters are consumed, return true only if the final node is marked as an ending. A recursive search helper can also traverse every branch and collect all stored words.

Maria
A binary heap is a partially ordered binary tree. In a min-heap, every parent is less than or equal to its children; in a max-heap, every parent is greater than or equal to its children. The order between siblings does not matter.

Corey
Heaps are complete binary trees: every level is full except possibly the last, and the last level fills from left to right. They are commonly stored in an array, with index zero left unused. For an item at index i, the left child is at 2i, the right child at 2i plus 1, and the parent is at floor of i divided by 2.

Maria
Inserting into the min-heap appends the new value at the end, then compares it with its parent. If it is smaller, the two values are swapped, and the comparison continues upward until the heap property is restored.

Corey
Removing from the min-heap always removes the root, which is the smallest value. The final array item moves to the root, the array is shortened, and the new root is repeatedly swapped with the smaller child while it is larger than a child. This moves it downward until the heap is valid again.

Maria
Heap sort uses that removal behavior. Insert every item from an unsorted array into a min-heap, then repeatedly remove the smallest item and append it to a result array. The result is ordered from least to greatest, and heap sort has average and worst-case performance of O of n log n.

Corey
A graph represents objects and their relationships. The objects are nodes, or vertices, and the relationships are edges. In a social network, people can be nodes and friendships can be edges. An undirected graph has edges without direction; a directed graph has edges that point from one node to another.

Maria
An adjacency list associates every vertex with its neighboring vertices. An adjacency matrix is a two-dimensional array with one row and column for every node: zero means no edge and one means an edge. Matrices can also represent directed graphs, where the location of the one indicates the direction.

Corey
An incidence matrix uses rows for nodes and columns for edges, so the number of rows and columns does not have to match. For an undirected edge, put a one in the rows of its two connected nodes. For a directed graph, use one for an edge leaving a node and negative one for an edge entering it. Graph edges may also have weights rather than simply zero-or-one relationships.

Maria
Graph traversal algorithms visit nodes to determine how they relate to one another. Breadth-first search explores all nodes one edge away before moving to nodes two edges away, and so on. In the example, it begins with a chosen root, records that root's distance as zero, and initializes other distances to infinity to indicate that they are not yet known to be reachable.

Corey
The breadth-first implementation uses a queue. It removes the current node, examines its adjacency-matrix row to find every connected neighbor, and records a neighbor's distance only if it is still infinity. That distance is the current node's distance plus one, and the neighbor is then added to the queue for later exploration.

Maria
The process continues until the queue is empty. Because nodes are processed in increasing distance from the root, the returned object maps each node to its shortest number of hops from the starting node. A node left at infinity cannot be reached from that root in the directed graph.

Corey
So the big picture is this: stacks provide LIFO behavior, queues provide FIFO behavior, sets enforce uniqueness, trees organize hierarchies, hash tables provide fast key-based access, linked lists connect dynamically sized nodes, tries share prefixes, heaps maintain a priority at the root, and graphs model relationships and paths.

Maria
And the implementation details follow each structure's defining rule. Use array push and pop for a stack, shift for a basic queue, comparisons for a binary search tree, hashing for key-value buckets, references for linked-list nodes, recursion for trie and tree operations, heap index formulas for priorities, and adjacency representations plus a queue for breadth-first graph search.

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