Data Structures Course
Data Structures Study Notes
What Are Data Structures?
Data structures are a way to store, organize, and manipulate data. They are not specific to any programming language; they are theoretical concepts that can be implemented in many ways. The choice of data structure affects the efficiency of operations based on the specific use case.
Data structures are not the same as data types. Data types (e.g., integer, boolean, string) are primitive pieces of data, while data structures store and organize those types.
Data structures fall into two categories:
Linear data structures – elements are arranged in a sequential order (e.g., arrays, linked lists, stacks, queues).
Non-linear data structures – elements are not in a straight line (e.g., trees, graphs).
Arrays
An array is an ordered collection of elements. Each element is accessed by its index. Arrays can be fixed-size (static) or dynamic-sized.
Fixed-Size Array
The size is defined at initialization and cannot change.
Initialization takes O(n) time because each memory slot must be allocated.
Memory is contiguous: the array stores a reference to the first memory address. Since slots are sequential, any index can be accessed by adding the index to the base address.
Operations
Operation | Time Complexity | Explanation |
|---|---|---|
Access/change by index | O(1) | Direct address calculation |
Insert at arbitrary position | O(n) | Shift elements right from the insertion point |
Delete at arbitrary position | O(n) | Shift elements left to fill the gap |
Insert at end (append) | O(1) | Only one slot changed (assuming space available) |
Delete at end (pop) | O(1) | Only remove the last element |
Inserting at the beginning requires shifting all elements → O(n).
Deleting the first element also requires shifting all remaining elements → O(n).
Dynamic-Size Array
Can grow or shrink as needed.
Internally uses a fixed-size array and resizes when capacity is reached.
Common resizing strategy: double the size when full.
Resizing involves:
Creating a new fixed-size array of larger size.
Copying all elements from the old array to the new one.
Adding the new element.
Disposing of the old array.
This copy operation takes O(n) time, but it happens infrequently, so the amortized cost of appending is O(1).
Key Takeaway
Arrays provide constant-time index access but linear-time insertion/deletion for most positions (except at the end).
Singly Linked List
A singly linked list is a linear data structure where elements are stored in nodes. Each node contains:
Value (data)
Next pointer – reference to the next node in the list
The list is accessed through the head node. The last node’s next pointer is null.
Traversal
To access the last element, you must traverse from the head, following next pointers until next is null. This takes O(n) time.
Pseudocode for traversal:
current = head
while current.next != null:
current = current.next
print current.valueOperations (Naive Singly Linked List)
Operation | Time Complexity | Explanation |
|---|---|---|
Access/search | O(n) | Must traverse from head |
Insert at beginning | O(1) | Create new node, point it to head, update head |
Insert at end (no tail reference) | O(n) | Traverse to last node, then add |
Delete at beginning | O(1) | Set head to head.next |
Delete at end | O(n) | Traverse to second-last node, set its next to null |
Insert/delete in middle | O(n) | Traverse to the position |
Circular Singly Linked List
In a circular linked list, the last node’s next pointer points back to the head, forming a circle.
Advantage: By storing a reference to the tail node, you can access both the first and last elements in O(1) time.
Insert at beginning: create new node, set its
nextto tail.next, then set tail.next to new node.Insert at end: create new node, set its
nextto tail.next, then set tail.next to new node, and update tail to the new node.Delete at beginning: set tail.next to tail.next.next (i.e., skip the head).
Delete at end: traverse to the node before tail, update its next, and set tail to that node (still O(n) unless doubly linked).
Thus, with a circular structure, both insertion and deletion at the front and back become O(1) – a major advantage over arrays.
Doubly Linked List
A doubly linked list adds a previous pointer to each node, allowing traversal in both forward and backward directions.
Node Structure
Value
Next pointer
Previous pointer (often
prev)
Operations
Insertion/deletion at front or back: O(1) (like circular singly, but with more pointer updates).
Insertion/deletion in the middle: O(n) if you must traverse; but if you already have a reference to a node, you can insert before or after it in O(1) because you have both
nextandprev.Access/search: O(n).
Advantages over Singly Linked List
Given any node, you can access its predecessor in O(1) time.
Useful for applications like a music player (forward/backward navigation) or implementing a deque.
Disadvantages
More memory per node (extra pointer).
More complex pointer updates (order matters to avoid losing references).
Insertion at Front (Example Pseudocode)
newNode.next = head
newNode.prev = head.prev (which is tail in circular version)
head.prev.next = newNode
head.prev = newNode
head = newNodeQueue
A queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are added at the back (enqueue) and removed from the front (dequeue).
Operations (Should Be O(1))
Enqueue (put/push) – add to the back
Dequeue (pop/pull) – remove from the front
Peek (front) – view the front element without removing
isEmpty – check if queue is empty
Efficient Implementation: Singly Linked List with Tail Reference
Using a circular singly linked list (storing the tail) provides constant-time enqueue and dequeue:
Enqueue: Tail.next = new node; new node.next = tail.next (the head); update tail.
Dequeue: Tail.next = Tail.next.next; (skip the current head).
Array Implementation Issues
If you implement a queue using an array:
Enqueue at back (append) is O(1) (amortized).
Dequeue from front requires shifting all elements → O(n).
Alternatively, enqueue at front (unshift) requires shifting → O(n); dequeue at end is O(1).
Thus, an array does not give constant time for both operations unless you use a circular buffer (not covered here).
Stack
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. Elements are added and removed from the same end (the top).
Operations
Push – add element to the top
Pop – remove the top element
Peek – view the top element
isEmpty – check if stack is empty
All operations should be O(1).
Implementation: Array Works Well
Because all operations happen at the same end (the top), an array can implement a stack efficiently:
Push: append to end → O(1) amortized.
Pop: remove from end → O(1).
Peek: view last element → O(1).
A linked list also works but is unnecessary.
Use Cases
Web browser back button: push each visited page onto the stack; clicking back pops the top page.
Undo operations in editors.
Implementing a queue using two stacks (exercise): push onto input stack; when dequeue is called, pop all from input stack and push onto output stack, then pop from output. This makes dequeue O(n) in worst case, but shows how stacks can combine.
Binary Trees
A binary tree is a non-linear data structure where each node has at most two children (left and right). It is a hierarchical structure.
Terminology
Root – the topmost node (no parent).
Leaf – a node with no children.
Edge – the connection between a parent and child.
Height – the maximum number of edges from the root to any leaf.
Depth – the number of edges from a node to the root.
Level – nodes at the same depth.
Node Structure
Value
Left pointer (to left child)
Right pointer (to right child)
Traversals
1. Breadth-First Search (BFS) – Level-Order
Uses a queue. Process nodes level by level.
Algorithm:
Enqueue root.
While queue not empty:
Pop node, print its value.
If node has left child, enqueue it.
If node has right child, enqueue it.
2. Depth-First Search (DFS) – Pre-order, In-order, Post-order
Uses a stack (or recursion). Traverses as deep as possible before backtracking.
Pre-order: Visit node, then left, then right.
In-order: Left, visit node, then right. (For a BST, this yields sorted order.)
Post-order: Left, then right, then visit node.
Example for a tree with nodes 1 (root), left=2, right=3; left of 2=4, right of 2=5; etc.
Insertion
To insert a new node into a binary tree (not a BST), find the first empty slot using BFS. Add the node there. This takes O(n) time because you may need to traverse all nodes.
Deletion
To delete a node:
Find the deepest rightmost leaf (using BFS or DFS).
Find the node to delete (BFS/DFS).
Copy the data from the deepest leaf to the node to delete.
Delete the deepest leaf (by removing the parent's reference).
This also takes O(n) time.
Properties of Binary Trees
Maximum number of nodes in a binary tree of height h: 2h+1−1
Minimum possible height for n nodes: ⌈log2(n+1)⌉−1 (when tree is balanced)
Maximum height for n nodes: n−1 (a degenerate tree, essentially a linked list)
Types of Binary Trees
1. Full Binary Tree
Every node has either 0 or 2 children. No node has exactly one child.
2. Complete Binary Tree
All levels are completely filled except possibly the last level, and the last level is filled from left to right.
3. Balanced Binary Tree
For every node, the height difference between the left and right subtrees is at most 1.
4. Perfect Binary Tree
All internal nodes have two children and all leaves are at the same level. A perfect binary tree is both full and complete.
Binary Search Trees (BST)
A binary search tree is a binary tree with an additional property:
In every node, all values in the left subtree are less than the node’s value.
All values in the right subtree are greater than (or equal to) the node’s value.
Operations and Time Complexity
Operation | Time Complexity | Notes |
|---|---|---|
Search | O(h) | h = height of tree |
Insert | O(h) | Same as search, then place at leaf |
Delete | O(h) | Need to locate node and possibly find successor/predecessor |
If the BST is balanced, h=O(logn), so operations are O(logn). If it is unbalanced (e.g., inserted in sorted order), h can be n, making operations O(n).
Search Algorithm (Pseudocode)
current = root
while current != null:
if target == current.value:
return current
else if target > current.value:
current = current.right
else:
current = current.left
return null (not found)Insertion
Insertion follows the same comparison path. When a null child is reached, insert the new node there.
Deletion – Three Cases
Leaf node: Remove the reference from its parent.
Node with one child: Link the parent directly to the child.
Node with two children:
Find the maximum value in the left subtree (in-order predecessor) OR the minimum value in the right subtree (in-order successor).
Copy that node’s value to the node to be deleted.
Delete that predecessor/successor (it will fall into case 1 or 2).
Example: To delete node 11 with left child 9 and right child 13, replace 11 with 9 (max in left) or 13 (min in right), then delete the leaf.
Heaps
A heap is a specialized tree-based data structure that satisfies the heap property:
Max heap: For every node, the parent is greater than or equal to its children.
Min heap: For every node, the parent is less than or equal to its children.
Heaps are typically implemented as complete binary trees (using an array) to maintain efficiency.
Array Representation
Because the heap is a complete binary tree, we can store it in an array using level-order indexing.
Left child of node at index i: 2i+1
Right child of node at index i: 2i+2
Parent of node at index i: ⌊(i−1)/2⌋
Operations
Insert (Push)
Add the new element to the end of the array (next available position).
While the new element is greater than its parent (for max heap), sift up: swap with parent.
Continue until the heap property is satisfied or the element becomes the root.
Time complexity: O(logn) (since we may travel up the height of the tree).
Extract Max (Pop)
Remove the root (maximum element).
Replace it with the last element of the array.
While this new root is smaller than its larger child, sift down: swap with the larger child.
Continue until heap property restored.
Time complexity: O(logn).
Peek
Access the root element – O(1).
Building a Heap from an Array
You can build a heap by inserting each element one by one: O(nlogn). However, there is a more efficient heapify operation that can build a heap in O(n) (not covered in source but worth noting).
Heap Sort
Build a max heap from the unsorted array.
Repeatedly extract the maximum (swap root with last, reduce heap size, sift down).
The extracted elements form a sorted array in descending order (then reverse if needed).
Time complexity: O(nlogn) (both building and extracting are O(nlogn)).
Use Cases
Priority queues
Scheduling tasks
Graph algorithms (Dijkstra’s shortest path)
Graphs
A graph is a non-linear data structure consisting of vertices (nodes) and edges (connections between vertices). Graphs model real-world relationships like road networks, social networks, currency exchange rates, etc.
Basic Terminology
Vertex (pl. vertices) – a node
Edge – a connection between two vertices
Adjacent vertices – vertices connected by an edge (neighbors)
Path – a sequence of edges from one vertex to another
Cycle – a path that starts and ends at the same vertex
Types of Graphs
1. Undirected Graph
Edges have no direction. If vertex A is connected to B, traversal can go both ways.
2. Directed Graph (Digraph)
Edges have a direction. An edge from A to B does not imply an edge from B to A.
3. Weighted Graph
Edges have associated weights (costs, distances). Can be directed or undirected.
4. Unweighted Graph
Edges have no weights; all edges are considered equal.
5. Cyclic Graph
Contains at least one cycle. (In undirected graphs, any edge forms a cycle between its two endpoints, so cycles are usually discussed for directed graphs.)
6. Acyclic Graph
Contains no cycles. A directed acyclic graph (DAG) is important for scheduling and dependency resolution.
7. Disconnected Graph
At least one vertex is not connected to the rest of the graph.
Graph Representations
Adjacency Matrix
A V×V boolean matrix (or weighted values).
matrix[i][j] = 1(or weight) if there is an edge from vertex i to vertex j.Space: O(V2).
Edge existence: O(1) lookup.
Suitable for dense graphs.
Adjacency List
An array or list of lists: for each vertex, maintain a list of adjacent vertices (and optionally weights).
Space: O(V+E).
Edge existence: O(degree).
Suitable for sparse graphs.
Comparison
Feature | Adjacency Matrix | Adjacency List |
|---|---|---|
Space | O(V2) | O(V+E) |
Check edge | O(1) | O(deg(v)) |
Add edge | O(1) | O(1) (if using list) |
Remove edge | O(1) | O(E) in worst case |
Hashing
Hashing is the process of converting input data (key) into a fixed-size output (called a hash or digest) using a hash function. The goal is to produce a unique output for each input (ideal), enabling efficient data retrieval.
Properties of a Good Hash Function
Deterministic (same input always gives same output)
Fast to compute
Uniformly distributes keys across the available range
Minimizes collisions
Hash Collisions
When two different keys produce the same hash value, a collision occurs. Collisions must be handled via:
Chaining: Each bucket in the hash table points to a linked list of entries that hash to the same index.
Open addressing: If a collision occurs, probe for the next available slot (e.g., linear probing, quadratic probing, double hashing).
Applications in Data Structures
Hash tables (maps, dictionaries, sets) use hashing to achieve average-case O(1) for insert, delete, and lookup operations.
A key is passed to the hash function, which returns an index into an array.
The key-value pair (or just key for a set) is stored at that index.
To look up a key, compute its hash and access that index; if the key matches, return the value; if not (due to collisions), follow the resolution strategy.
Complexity
Average case: O(1) for insert, delete, contains.
Worst case: O(n) if many collisions occur (e.g., all keys hash to the same index).
In practice, with a good hash function and appropriate load factor, performance is nearly constant.
Example (Simplified)
Assume an array of size 10 and a hash function hash(key) = key % 10:
Key
12→ index 2 → store value there.Key
22→ also index 2 → collision. Use chaining: add to linked list at index 2.
To retrieve value for 22, compute hash, go to index 2, then traverse the linked list until 22 is found.
These notes cover the essential data structures and their fundamental operations, time complexities, and use cases. Understanding these concepts is critical for efficient algorithm design and technical interviews.

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