1. Home
  2. Explore
  3. Computer Science
  4. Intro to Data Structures

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Intro to Data Structures

Data Structures: Comprehensive Study Notes

Introduction to Data Structures

Data structure is the most fundamental building block concept in computer science. A data structure is a way to store and organize data in a computer so that the data can be used efficiently. Good knowledge of data structures is essential to design and develop efficient software systems.

We deal with data all the time, and how we store, organize, and group data matters. Different kinds of data require different structures:

  • Dictionary – words are stored as a sorted list, enabling quick search. If unsorted, searching among millions of words would be impractical.

  • City map – data like landmark positions and road networks are organized as geometries on a 2D plane, enabling effective landmark search and route finding.

  • Cash book (daily cash in/out statement) – best organized as a tabular schema (columns and tables) for easy aggregation and information extraction.

Computers work with all kinds of data: text, images, videos, relational data, geospatial data. Because computers deal with extremely large data, using the right kind of logical structures is critical for efficiency.

Two Ways to Study Data Structures

  1. Mathematical and logical models (abstract view) – we define the features and operations of a data structure without implementation details. This is called an abstract data type (ADT).

    • Example: A television's abstract view is an electrical device that can be turned on/off, receive satellite signals, and play audio/video. We don't care about the internal circuits.

    • Example ADT: A list that can store a group of elements of a given data type, read elements by position, and modify elements at a given position.

  2. Implementation – concrete types that realize the ADT. The same ADT can be implemented in multiple ways. For example, a list ADT can be implemented as an array (in many languages) or as a linked list (in C/C++).

Abstract Data Type (ADT): An entity that defines data and operations but does not include implementation details.

Data structures studied in this course include: arrays, linked list, stack, queue, tree, graph, and many more. For each, we study:

  • Logical view

  • Available operations

  • Cost of operations (mostly time)

  • Implementation in a programming language


The List ADT and Array-Based Implementation

List as an Abstract Data Type

A list is a collection of objects of the same type (e.g., a list of words, names, or numbers).

Static List ADT

  • Store a given number of elements of a given data type (fixed size, known in advance).

  • Operations:

    • Write/modify element at any position.

    • Read element at any position.

  • Implementation: Array – arrays provide exactly these features.

Dynamic List ADT

The list should grow as needed. Operations:

  • isEmpty() – returns true if no elements.

  • insert(element, position) – insert at any position.

  • remove(position) – remove element at given position.

  • count() – number of elements.

  • read(position) / write(position, value) – access or modify element.

  • Specify data type upon creation.

Array-Based Implementation of Dynamic List

We can implement a dynamic list using arrays by:

  1. Declaring a large array of a certain max size.

  2. Using a variable (e.g., end) to mark the last index of the list. Initially end = -1 (empty list).

  3. For insertion:

    • At tail: increment end, place element.

    • At a given position: shift all elements from that position to the right, then insert, increment end.

  4. For removal: shift elements left to fill the gap, decrement end.

  5. For read/write by index: direct array access (constant time).

  6. For data type: choose array of that type.

Problem: What if the array fills up? We cannot extend the same array. Solution: create a new larger array (typically double the size) and copy all elements from the old array to the new one, then free the old array. This copying is costly, so a good strategy is to double the size each time (the amortized cost analysis shows this is optimal).

Time Complexity of Operations (Big O notation)

  • Access by index (read/write): O(1)O(1)O(1) – constant time, because array elements are in one contiguous block; address = base + index × element size.

  • Insert at end (when not full): O(1)O(1)O(1). When full: O(n)O(n)O(n) due to copying.

  • Insert at a given position: O(n)O(n)O(n) in worst case (shifting elements).

  • Remove at a given position: O(n)O(n)O(n) (shifting).

  • Add element (at end): O(1)O(1)O(1) if not full; O(n)O(n)O(n) if full.

Limitations of array-based dynamic list:

  • Extra memory may be unused (reserved space).

  • Insertions and deletions in the middle are costly (shifting).

  • When full, copying to a new array is expensive.

  • Memory is not utilized efficiently; large parts of the array may remain empty.

These limitations motivate the linked list data structure.


Linked List

Motivation: Memory Fragmentation and Array Limitations

When an array is created, it requires a contiguous block of memory. As other variables are allocated, there may not be enough adjacent free space to extend the array. The only option is to create a new, larger block and copy all elements. This is costly and wastes memory if the list is small relative to the array size.

Instead of asking for one large contiguous block, we can request memory for one element at a time. Each piece of memory is called a node. Nodes are stored at non-contiguous locations in memory. To keep the list together, each node stores:

  • The data.

  • The address (link) of the next node.

The first node is the head; the last node's link is NULL (address 0). The only information kept about the list is the address of the head node.

Node Definition (C/C++)

struct node {
    int data;          // data (can be any type)
    struct node* next; // pointer to next node
};

Logical View of a Linked List

  • Each node contains data and a link to the next node.

  • The head pointer identifies the list.

  • The last node's next is NULL.

Operations on Linked List

Accessing an Element

Cannot access directly by index. Must traverse from head, following next pointers until the desired position is reached. Time: O(n)O(n)O(n).

Insertion

  • At head: create a new node, set its next to current head, then update head to the new node. Time: O(1)O(1)O(1).

  • At tail: traverse to the end, then link the new node. Time: O(n)O(n)O(n).

  • At a given position: traverse to the node before the insertion point, adjust links. Time: O(n)O(n)O(n).

Deletion

  • At head: update head to next node, delete the old head. Time: O(1)O(1)O(1).

  • At tail: traverse to second-last node, set its next to NULL, delete last node. Time: O(n)O(n)O(n).

  • At a given position: traverse to the node before the deletion point, adjust links, delete node. Time: O(n)O(n)O(n).

Advantages of Linked List over Arrays

  • Dynamic size: no need to guess the size beforehand; nodes are created as needed.

  • Efficient insertion/deletion at beginning: O(1)O(1)O(1) vs O(n)O(n)O(n) for array.

  • No memory waste from unused reserved space (though extra memory is used for pointers).

  • Better memory utilization when data part is large: pointer overhead is constant per node.

Disadvantages

  • No constant-time access: must traverse from head.

  • Extra memory for pointers (typically 4 or 8 bytes per node).

  • Not cache-friendly due to non-contiguous memory.

  • More complex implementation (e.g., segmentation faults, memory leaks in C/C++).

Comparison: Array vs Linked List

Parameter

Array

Linked List

Access (by index)

O(1)O(1)O(1)

O(n)O(n)O(n)

Memory usage

Contiguous block; may waste unused space; no pointer overhead

Non-contiguous; each node has pointer overhead; no wasted space if sized exactly

Memory allocation

Must know size in advance; may fail if large contiguous block unavailable

Nodes allocated one at a time; works with fragmented memory

Insertion at beginning

O(n)O(n)O(n) (shift elements)

O(1)O(1)O(1)

Insertion at end

O(1)O(1)O(1) (if space), else O(n)O(n)O(n)

O(n)O(n)O(n) (traversal)

Insertion in middle

O(n)O(n)O(n)

O(n)O(n)O(n) (traversal + O(1)O(1)O(1) link adjustment)

Deletion

O(n)O(n)O(n) (shifting)

O(n)O(n)O(n) (traversal)

Ease of implementation

Simple

More error-prone (pointers, memory management)


Linked List Implementation Details

Insert at Beginning (C code example)

struct node {
    int data;
    struct node* next;
};

struct node* head = NULL; // global

void insert(int x) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = head;
    head = temp;
}

Insert at nth Position

To insert at position n (1-based):

  • Create a new node.

  • If n == 1, insert at head.

  • Else, traverse to the (n-1)th node, then adjust links.

Delete at nth Position

  • If n == 1, update head to next, free the old head.

  • Else, traverse to the (n-1)th node, store the nth node, adjust links, free the node.

Reverse a Linked List (Iterative)

Use three pointers: prev, current, next.

void reverse() {
    struct node *prev = NULL, *current = head, *next = NULL;
    while (current != NULL) {
        next = current->next;   // store next
        current->next = prev;   // reverse link
        prev = current;         // move prev forward
        current = next;         // move current forward
    }
    head = prev;
}

Reverse a Linked List (Recursive)

void reverse(struct node* p) {
    if (p->next == NULL) {
        head = p;
        return;
    }
    reverse(p->next);
    struct node* q = p->next;
    q->next = p;
    p->next = NULL;
}

Recursive Traversal (Print Forward and Backward)

  • Print forward: print data, then recursive call on p->next.

  • Print reverse: recursive call on p->next, then print data.


Doubly Linked List

In a doubly linked list, each node has two links: one to the previous node and one to the next node. This allows traversal in both directions.

Node Definition

struct node {
    int data;
    struct node* prev;
    struct node* next;
};

Advantages

  • Forward and reverse lookup with a single pointer: temp->next and temp->prev.

  • Deletion: given a pointer to the node to delete, we can do it with only that pointer (no need to keep track of previous node).

Disadvantages

  • Extra memory for the prev pointer (8 bytes per node vs 4 for singly linked list for integers).

  • More careful link updates during insertion/deletion (more error-prone).

Insert at Head (Doubly Linked List)

void insertAtHead(int x) {
    struct node* newNode = getNewNode(x); // creates node with prev=next=NULL
    if (head == NULL) {
        head = newNode;
        return;
    }
    head->prev = newNode;
    newNode->next = head;
    head = newNode;
}

Insert at Tail, Print Forward, Print Reverse are similar extensions.


Stack

Stack as an ADT

A stack is a list or collection with the restriction that insertion and deletion can be performed only from one end, called the top of the stack. This is a Last In, First Out (LIFO) structure.

Stack: A list where insertion and deletion occur only at one end (top). LIFO structure.

Operations

  • push(x) – insert element x onto the top.

  • pop() – remove the most recent element from the top.

  • top() – return the element at the top (without removing).

  • isEmpty() – check if the stack is empty.

All operations should take constant time (O(1)O(1)O(1)).

Logical Representation

A stack is often drawn as a container open from one side. Elements are added (pushed) and removed (popped) from the same end.

Applications of Stack

  1. Function call execution – each function call pushes a stack frame; return pops it.

  2. Recursion – uses the call stack implicitly.

  3. Undo operations in text/image editors.

  4. Balanced parentheses checking in compilers.

  5. Expression evaluation (postfix/prefix).

  6. Reversing a string or linked list.

Array-Based Stack Implementation

  • Use an array a of size MAX and an integer top initially -1.

  • push(x): if top < MAX-1, increment top and set a[top] = x. Handle overflow.

  • pop(): if top != -1, decrement top.

  • top(): return a[top].

  • isEmpty(): return top == -1.

Overflow handling: Either throw error or use dynamic array (double size when full). A dynamic array approach gives O(1)O(1)O(1) amortized time for push.

Linked List-Based Stack Implementation

  • Use a singly linked list where top points to the head node.

  • push(x): insert node at head (constant time).

  • pop(): delete node at head (constant time).

  • top(): return top->data.

  • isEmpty(): return top == NULL.

Advantage: No fixed size; no overflow unless memory exhausted. Extra memory per node for pointer.

Using Stack to Reverse a String

  1. Push all characters of the string onto a stack.

  2. Pop characters and overwrite the string from index 0 onwards.

Time: O(n)O(n)O(n), Space: O(n)O(n)O(n) (stack). More efficient in-place reversal uses two-pointer swap (O(1)O(1)O(1) extra space).

Using Stack to Reverse a Linked List

  1. Traverse the linked list, pushing pointers to each node onto a stack.

  2. Pop nodes, adjusting links to reverse order.

Time: O(n)O(n)O(n), Space: O(n)O(n)O(n). Iterative in-place reversal is more space-efficient (O(1)O(1)O(1)).

Balanced Parentheses Problem

Given an expression string containing parentheses (), curly braces {}, and square brackets [], check if they are balanced.

Algorithm:

  • Scan the expression left to right.

  • If an opening symbol is encountered, push it onto the stack.

  • If a closing symbol is encountered:

    • If stack is empty → unbalanced.

    • Else, pop the top; if the popped symbol does not match the closing symbol → unbalanced.

  • After scanning, if stack is empty → balanced; else → unbalanced.

Time: O(n)O(n)O(n), Space: O(n)O(n)O(n).

Expression Evaluation: Infix, Prefix, Postfix

Notation

Operator Placement

Example (a+b*c)

Infix

Between operands

a + b * c

Prefix (Polish)

Before operands

+ a * b c

Postfix (Reverse Polish)

After operands

a b c * +

Why Postfix/Prefix? They are parenthesis-free and do not require operator precedence/associativity rules for evaluation. They are easier for machines to parse.

Operator Precedence (high to low):

  1. Parentheses

  2. Exponents (^) – right associative

  3. Multiplication/Division – left associative

  4. Addition/Subtraction – left associative

Evaluating Postfix Expression (Algorithm using Stack)

  1. Scan the postfix expression left to right.

  2. If token is an operand, push it onto the stack.

  3. If token is an operator:

    • Pop two operands from stack (first popped is second operand, second popped is first operand).

    • Apply the operator.

    • Push the result back.

  4. At the end, the stack contains the final result.

Time: O(n)O(n)O(n), Space: O(n)O(n)O(n).

Evaluating Prefix Expression

Similar to postfix, but scan right to left. When an operand is encountered, push; when an operator is encountered, pop two operands (first popped is first operand, second popped is second operand), apply, push result.

Converting Infix to Postfix (Shunting-Yard Algorithm)

Uses a stack for operators.

Rules (no parentheses):

  • If token is operand: append to output.

  • If token is operator:

    • While stack not empty AND top of stack has higher or equal precedence (for left-associative operators) than token: pop top to output.

    • Push token onto stack.

  • After scanning, pop remaining operators to output.

With parentheses:

  • If token is (: push onto stack.

  • If token is ): pop operators to output until ( is encountered; pop and discard (.

  • For operators, stop popping when top is (.

Example: a + b * c → a b c * +.


Queue

Queue as an ADT

A queue is a list or collection with the restriction that insertion is performed at one end (the rear or tail) and deletion is performed at the other end (the front or head). This is a First In, First Out (FIFO) structure.

Queue: A list where insertion occurs at the rear and deletion occurs at the front. FIFO structure.

Operations

  • enqueue(x) – insert element x at the rear.

  • dequeue() – remove and return the element at the front.

  • front() – return the element at the front (without removing).

  • isEmpty() – check if the queue is empty.

All operations should take O(1)O(1)O(1) time.

Applications of Queue

  • Shared resource serving requests (e.g., printer queue, CPU scheduling).

  • Breadth-first search in graphs.

  • Simulating waiting lines.

Array-Based Queue Implementation (Circular Array)

  • Use an array a of size MAX, and two indices: front and rear, both initially -1.

  • Enqueue:

    • If queue is full: (rear+1) % MAX == front → overflow.

    • If empty: set front = rear = 0.

    • Else: rear = (rear+1) % MAX.

    • Write x at a[rear].

  • Dequeue:

    • If empty (front == -1): underflow.

    • If front == rear (only one element): set front = rear = -1.

    • Else: front = (front+1) % MAX.

  • Front: return a[front] (if not empty).

  • isEmpty: front == -1.

Circular array reuses the vacated positions, solving the "unusable left cells" problem.

Linked List-Based Queue Implementation

  • Maintain two pointers: front (head) and rear (tail).

  • Enqueue:

    • Create new node with data.

    • If empty: set both front and rear to new node.

    • Else: add node after rear, update rear.

  • Dequeue:

    • Store node at front.

    • Update front to front->next.

    • If front becomes NULL, set rear = NULL (queue empty).

    • Free the old front node.

  • Front: return front->data.

  • isEmpty: front == NULL.

Advantage: No fixed size; no need to guess capacity. O(1)O(1)O(1) for enqueue and dequeue.


Tree

Introduction

Tree is a non-linear, hierarchical data structure. It is a collection of nodes connected by edges, with a root node at the top and branches downward.

Tree vs Linear Structures: Array, linked list, stack, queue are linear (sequential). Tree is hierarchical.

Applications

  • Representing hierarchical data (file systems, organizational charts).

  • Binary Search Tree (BST): efficient search, insertion, deletion (O(log⁡n)O(\log n)O(logn) on average).

  • Trie: dictionary storage, dynamic spell checking.

  • Network routing algorithms.

Terminology

  • Root: topmost node (no parent).

  • Parent: node with outgoing edges to children.

  • Child: node with incoming edge from parent.

  • Sibling: nodes sharing same parent.

  • Leaf: node with no children.

  • Internal node: node with at least one child.

  • Ancestor: any node on path from root to a node.

  • Descendant: any node in subtree of a node.

  • Depth of a node: number of edges from root to that node (root depth = 0).

  • Height of a node: number of edges in longest path from that node to a leaf (leaf height = 0).

  • Height of tree: height of root.

  • Edge: connection between two nodes. In a tree with nnn nodes, there are exactly n−1n-1n−1 edges.

Binary Tree

A binary tree is a tree where each node has at most two children (left child and right child).

Types of Binary Trees

  • Strict (proper) binary tree: every node has either 0 or 2 children.

  • Complete binary tree: all levels except possibly the last are completely filled, and nodes in the last level are as far left as possible.

  • Perfect binary tree: all levels are completely filled.

  • Balanced binary tree: for every node, the difference between heights of left and right subtrees is at most 1 (often used to ensure O(log⁡n)O(\log n)O(logn) height).

Properties

  • Maximum nodes at level iii: 2i2^i2i.

  • Maximum nodes in a binary tree of height hhh: 2h+1−12^{h+1} - 12h+1−1 (perfect tree).

  • Minimum height of a tree with nnn nodes: ⌊log⁡2n⌋\lfloor \log_2 n \rfloor⌊log2​n⌋ (complete binary tree).

  • Maximum height of a tree with nnn nodes: n−1n-1n−1 (skewed tree, like a linked list).

Storage Representation

Dynamic nodes with pointers (most common):

struct node {
    int data;
    struct node* left;
    struct node* right;
};

Array representation for complete binary trees: For a node at index iii, left child at 2i+12i+12i+1, right child at 2i+22i+22i+2.

Binary Search Tree (BST)

A Binary Search Tree is a binary tree where for each node:

  • All nodes in the left subtree have values less than (or equal to, if duplicates allowed) the node's value.

  • All nodes in the right subtree have values greater than the node's value.

  • Both left and right subtrees are also BSTs.

This property enables efficient search similar to binary search on a sorted array.

Search in BST

Start at root. Compare target with current node:

  • If equal, found.

  • If target < current, go to left child.

  • If target > current, go to right child.

  • If child is NULL, not found.

Time complexity: O(h)O(h)O(h), where hhh is height of tree. Average case (balanced): O(log⁡n)O(\log n)O(logn). Worst case (skewed): O(n)O(n)O(n).

Insertion in BST

  • Search for the value; if it already exists, (optionally) ignore or handle duplicates.

  • When a NULL child is reached, insert a new node at that position.

Recursive implementation:

struct node* insert(struct node* root, int data) {
    if (root == NULL) {
        root = getNewNode(data);
        return root;
    }
    else if (data <= root->data)
        root->left = insert(root->left, data);
    else
        root->right = insert(root->right, data);
    return root;
}

Deletion in BST

Three cases:

  1. Node is a leaf: simply remove it.

  2. Node has one child: link its parent directly to its child.

  3. Node has two children: find the in-order successor (smallest in right subtree) or in-order predecessor (largest in left subtree), copy its value to the node, then delete that successor/predecessor node (which falls into case 1 or 2).

Recursive implementation:

struct node* delete(struct node* root, int data) {
    if (root == NULL) return root;
    if (data < root->data)
        root->left = delete(root->left, data);
    else if (data > root->data)
        root->right = delete(root->right, data);
    else {
        // Case 1: leaf
        if (root->left == NULL && root->right == NULL) {
            free(root);
            root = NULL;
        }
        // Case 2: one child
        else if (root->left == NULL) {
            struct node* temp = root;
            root = root->right;
            free(temp);
        }
        else if (root->right == NULL) {
            struct node* temp = root;
            root = root->left;
            free(temp);
        }
        // Case 3: two children
        else {
            struct node* temp = findMin(root->right);
            root->data = temp->data;
            root->right = delete(root->right, temp->data);
        }
    }
    return root;
}

Finding Minimum and Maximum in BST

  • Minimum: go left as far as possible.

  • Maximum: go right as far as possible.

Both O(h)O(h)O(h).

In-order Successor

The node that would appear immediately after a given node in an in-order traversal.

Cases:

  1. If the node has a right subtree: successor is the minimum in that right subtree.

  2. If no right subtree: go up to the nearest ancestor such that the given node is in its left subtree. That ancestor is the successor.

Time: O(h)O(h)O(h).

Tree Traversal

Traversal is the process of visiting each node exactly once in some order.

Breadth-First Traversal (Level Order)

Visit nodes level by level, from left to right. Uses a queue.

Algorithm:

  1. Enqueue root.

  2. While queue is not empty:

    • Dequeue a node, visit it.

    • Enqueue its left child (if exists).

    • Enqueue its right child (if exists).

Time: O(n)O(n)O(n) (each node visited once). Space: O(w)O(w)O(w) where www is maximum width of tree; worst-case O(n)O(n)O(n).

Depth-First Traversals

For a node, we have three possible orderings (left always before right):

  • Preorder: Visit root, then left subtree, then right subtree. (Root, Left, Right)

  • Inorder: Visit left subtree, then root, then right subtree. (Left, Root, Right) – for BST, gives sorted order.

  • Postorder: Visit left subtree, then right subtree, then root. (Left, Right, Root)

Recursive implementations:

void preorder(struct node* root) {
    if (root == NULL) return;
    printf("%d ", root->data);
    preorder(root->left);
    preorder(root->right);
}

void inorder(struct node* root) {
    if (root == NULL) return;
    inorder(root->left);
    printf("%d ", root->data);
    inorder(root->right);
}

void postorder(struct node* root) {
    if (root == NULL) return;
    postorder(root->left);
    postorder(root->right);
    printf("%d ", root->data);
}

Time: O(n)O(n)O(n) for each. Space: O(h)O(h)O(h) for the call stack (worst O(n)O(n)O(n)).

Applications

  • Preorder: creating a copy of the tree, prefix expression from expression tree.

  • Inorder: BST yields sorted order.

  • Postorder: deleting the tree, postfix expression.

Check if Binary Tree is BST

Method 1 (inefficient): For each node, check that all values in left subtree are less and all in right are greater. Recursively check left and right subtrees. O(n2)O(n^2)O(n2) in worst case.

Method 2 (efficient): Use a range for each node. Initially (−∞,+∞)(-\infty, +\infty)(−∞,+∞). As we go left, update upper bound to node's value; as we go right, update lower bound to node's value. Check that each node's value lies within its range. O(n)O(n)O(n).

bool isBSTUtil(struct node* root, int min, int max) {
    if (root == NULL) return true;
    if (root->data < min || root->data > max) return false;
    return isBSTUtil(root->left, min, root->data) &&
           isBSTUtil(root->right, root->data, max);
}
bool isBST(struct node* root) {
    return isBSTUtil(root, INT_MIN, INT_MAX);
}

Method 3 (in-order traversal): Perform in-order traversal; keep track of the previous value. If current value is not greater than previous, it's not a BST. O(n)O(n)O(n) time, O(h)O(h)O(h) space.

Height of Binary Tree

Height (max depth) = number of edges in longest path from root to a leaf. Recursive definition:

  • Height of empty tree = -1.

  • Height of leaf = 0.

  • Height of node = 1+max⁡(height(left),height(right))1 + \max(\text{height(left)}, \text{height(right)})1+max(height(left),height(right)).

int height(struct node* root) {
    if (root == NULL) return -1;
    return 1 + max(height(root->left), height(root->right));
}

Time: O(n)O(n)O(n).


Graph

Introduction

A graph is a non-linear data structure consisting of a finite set of vertices (nodes) and a set of edges (connections). Unlike trees, there are no restrictions on connections.

Graph: G=(V,E)G = (V, E)G=(V,E), where VVV is a set of vertices and EEE is a set of edges.

Types of Graphs

  • Undirected graph: edges have no direction; connection is bidirectional.

  • Directed graph (digraph): edges have direction; connection is one-way.

  • Weighted graph: edges have associated weights/costs.

  • Simple graph: no self-loops (edge from vertex to itself) and no multiple edges between same pair of vertices.

  • Dense graph: number of edges close to maximum possible (O(∣V∣2)O(|V|^2)O(∣V∣2)).

  • Sparse graph: number of edges much smaller than ∣V∣2|V|^2∣V∣2 (often O(∣V∣)O(|V|)O(∣V∣)).

Graph Terminology

  • Path: sequence of vertices where each consecutive pair is connected by an edge. A simple path has no repeated vertices.

  • Cycle: a closed path (starts and ends at same vertex) with no repeated vertices except the start/end.

  • Connected graph (undirected): there is a path between every pair of vertices.

  • Strongly connected (directed): there is a directed path from every vertex to every other vertex.

  • Weakly connected (directed): the underlying undirected graph is connected.

  • Acyclic graph: graph with no cycles. A tree is a connected acyclic undirected graph. A DAG (Directed Acyclic Graph) is useful for scheduling.

Graph Representations

Edge List

Store all vertices in a list, and all edges as objects containing start vertex, end vertex, and (optionally) weight.

  • Space: O(∣V∣+∣E∣)O(|V| + |E|)O(∣V∣+∣E∣).

  • Time for finding neighbors of a node: O(∣E∣)O(|E|)O(∣E∣) – must scan all edges.

  • Time for checking if two nodes are connected: O(∣E∣)O(|E|)O(∣E∣).

Inefficient for large graphs; only used for simple tasks.

Adjacency Matrix

Use a 2D array of size ∣V∣×∣V∣|V| \times |V|∣V∣×∣V∣. adj[i][j] = 1 (or weight) if edge from i to j, else 0 (or infinity).

  • Space: O(∣V∣2)O(|V|^2)O(∣V∣2) – wasteful for sparse graphs.

  • Time to check connectivity: O(1)O(1)O(1) (if indices known).

  • Time to find all neighbors: O(∣V∣)O(|V|)O(∣V∣) (scan a row).

  • Good for dense graphs; impractical for large sparse graphs.

Adjacency List

For each vertex, maintain a list (usually a linked list, but can be dynamic array or BST) of its neighbors.

  • Space: O(∣V∣+∣E∣)O(|V| + |E|)O(∣V∣+∣E∣) – efficient for sparse graphs.

  • Time to find neighbors: O(deg⁡(v))O(\deg(v))O(deg(v)), where deg⁡(v)\deg(v)deg(v) is the degree of vertex vvv (number of incident edges).

  • Time to check connectivity: O(deg⁡(v))O(\deg(v))O(deg(v)) (need to search the list) – can be improved by using sorted lists or hash sets.

  • Most commonly used representation for real-world graphs.

Graph Traversal

Breadth-First Search (BFS)

  • Visits vertices in order of increasing distance from the source.

  • Uses a queue.

  • Produces a shortest path in unweighted graphs.

Algorithm:

  1. Mark source as visited, enqueue it.

  2. While queue not empty:

    • Dequeue a vertex, process it.

    • For each unvisited neighbor, mark visited and enqueue.

Time: O(∣V∣+∣E∣)O(|V| + |E|)O(∣V∣+∣E∣) (using adjacency list). Space: O(∣V∣)O(|V|)O(∣V∣).

Depth-First Search (DFS)

  • Explores as far as possible along each branch before backtracking.

  • Uses a stack (recursion or explicit).

  • Useful for topological sorting, detecting cycles, finding connected components.

Algorithm (recursive):

  1. Mark current vertex as visited, process it.

  2. For each unvisited neighbor, recursively call DFS.

Time: O(∣V∣+∣E∣)O(|V| + |E|)O(∣V∣+∣E∣). Space: O(∣V∣)O(|V|)O(∣V∣) (call stack).


Summary of Key Points

  • Data structures organize data for efficient access and modification.

  • ADTs define what operations are available without specifying implementation.

  • Arrays provide O(1)O(1)O(1) access but costly insertion/deletion.

  • Linked lists allow dynamic memory usage and O(1)O(1)O(1) insertion at ends but O(n)O(n)O(n) access.

  • Stacks (LIFO) and Queues (FIFO) are specialized lists used for many algorithmic problems.

  • Trees represent hierarchical data; BST enables O(log⁡n)O(\log n)O(logn) search, insert, delete on average.

  • Graphs model pairwise relationships; choice of representation (matrix vs list) depends on density.

  • Understanding time and space complexity is crucial for selecting the right data structure for a given problem.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent