⚡ Solve Challenges Open IDE ➜
Module 1 — Interactive CS Algorithm Workbench

Advanced DSA Playground

Explore interactive visual demonstrations for binary search trees, heaps, hash tables with collision handling, graph BFS & DFS, Dijkstra's algorithm, sorting comparisons, and linear data structures with step-by-step state inspection.

🌲 Binary Search Tree (BST) & Traversals
Intermediate State: Ready. Enter data or click an operation to step through execution.

🧪 Automated Algorithm Invariant Test Suite

Validates data structure invariants against known mathematical verification vectors.

📖 Comprehensive Data Structures & Algorithms Manual

Master the mathematical properties, asymptotic complexities, memory layouts, invariant proofs, and real-world system applications of foundational computer science data structures and search/sort algorithms. Written for undergraduate computer science students and software engineering interview candidates.

🌲 1. Binary Search Trees (BST) & Tree Traversal Invariants

Hierarchical Structures • Logarithmic Search

A Binary Search Tree (BST) is a node-based binary tree data structure where each node contains a comparable key and satisfies the strict binary search invariant:

The Binary Search Tree Invariant: For any arbitrary node X in the tree:
• All keys located in the left subtree of X must be strictly less than key(X): ∀ y ∈ LeftSubtree(X), key(y) < key(X).
• All keys located in the right subtree of X must be strictly greater than key(X): ∀ z ∈ RightSubtree(X), key(z) > key(X).
• Both the left and right subtrees must independently satisfy the same binary search tree invariant (recursive property).

A. Node Structure & Memory Allocation

In memory, each BST node is dynamically allocated with three fields: a data value, a left child pointer, and a right child pointer. In languages like C and C++, node representation involves explicit pointers:

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

B. Deletion Algorithm (Three Cases)

Deleting a node from a BST is the most complex standard operation because the binary search invariant must remain preserved across all remaining nodes. The operation divides into three fundamental structural cases:

  • Case 1 (Node is a Leaf): The target node has zero children. Deletion is trivial: sever the parent's pointer to this node and free the allocated memory.
  • Case 2 (Node has Exactly One Child): The target node has either a left child or a right child (not both). Bypass the target node by redirecting the parent's pointer directly to the single child of the deleted node.
  • Case 3 (Node has Two Children): Locate the target node's Inorder Successor (the smallest node in its right subtree, found by traversing left from node->right until reaching a node without a left child) or Inorder Predecessor (largest node in its left subtree). Copy the successor's key into the target node, and then recursively delete the inorder successor from the right subtree (which now falls under Case 1 or Case 2).

C. Tree Traversals & Asymptotic Complexity

Traversal Strategy Node Visit Order Time Complexity Space (Call Stack) Primary Application
Inorder (LNR) Left Subtree → Current Node → Right Subtree O(N) O(H) → O(log N) avg, O(N) worst Outputs elements in sorted non-decreasing order
Preorder (NLR) Current Node → Left Subtree → Right Subtree O(N) O(H) → O(log N) avg, O(N) worst Tree serialization, cloning, prefix expressions
Postorder (LRN) Left Subtree → Right Subtree → Current Node O(N) O(H) → O(log N) avg, O(N) worst Bottom-up deletion (freeing tree), calculating tree size/height
Level-Order (BFS) Level-by-level top-to-bottom using FIFO Queue O(N) O(W) → O(N) where W is max tree width Breadth-first search, calculating minimum depth

⛰️ 2. Binary Heaps, Priority Queues & Invariant Mathematics

Array-Backed Trees • Priority Queuing

A Binary Heap is a complete binary tree that satisfies the Heap Invariant. Because the tree is completely filled on all levels except possibly the bottom level (which is filled strictly from left to right without gaps), binary heaps are compactly represented inside a contiguous flat array without storing pointer addresses.

A. Array Index Mapping Mathematics

For any element stored at zero-based array index i:

Relationship 0-Indexed Formula 1-Indexed Formula Bitwise Optimization
Parent Node Math.floor((i - 1) / 2) Math.floor(i / 2) (i - 1) >> 1
Left Child 2 * i + 1 2 * i (i << 1) | 1
Right Child 2 * i + 2 2 * i + 1 (i + 1) << 1

B. Min-Heap vs. Max-Heap Properties

• Min-Heap: Every parent node is smaller than or equal to both its children: A[parent(i)] ≤ A[i]. The minimum element is always at root index A[0].
• Max-Heap: Every parent node is greater than or equal to both its children: A[parent(i)] ≥ A[i]. The maximum element is always at root index A[0].

C. Sift-Up vs. Sift-Down & O(N) Build-Heap Proof

Inserting an element places it at the array end followed by Sift-Up (Bubble-Up), swapping with its parent until the heap property is restored in O(log N) time. Extracting the root swaps it with the final array element, shrinks the heap size by 1, and runs Sift-Down (Heapify) down the tree in O(log N) time.

Why is buildHeap O(N) and not O(N log N)?
When transforming an arbitrary array into a heap bottom-up, we call siftDown from index n/2 - 1 down to 0. The nodes near the leaves have very short paths downward: n/4 nodes have height 1, n/8 nodes have height 2, and only 1 root node has height log N.
Summing the mathematical series: S = ∑ (h / 2^h) = 2. Multiplying by N yields total work bounded by strictly O(N).

🔑 3. Hash Tables, Hash Functions & Collision Handling

Associative Arrays • Amortized O(1) Access

A Hash Table maps keys to array slots via a mathematical hashing function index = hash(key) mod Capacity. The central engineering challenge is managing collisions—when two distinct keys hash to the identical bucket index.

A. Collision Resolution Strategies Compared

Strategy Probe Function Formula Pros Cons & Pathology
Separate Chaining Each bucket holds a linked list / balanced BST Handles load factors α > 1; simple deletion Extra pointer overhead; poor CPU cache locality
Linear Probing h(k, i) = (h(k) + i) mod M Excellent CPU cache locality; zero pointer overhead Primary Clustering: Long occupied contiguous blocks build up, degrading lookups to O(N)
Quadratic Probing h(k, i) = (h(k) + c1*i + c2*i²) mod M Eliminates primary contiguous clustering Secondary Clustering: Keys with identical initial hash follow identical probe paths
Double Hashing h(k, i) = (h1(k) + i * h2(k)) mod M Closest to uniform hashing; no clustering Requires two independent hash functions; h2(k) must be coprime to M

The Load Factor (α = N / M): Represents the average ratio of stored keys to bucket capacity. When α exceeds 0.75 in open addressing or 1.0 in chaining, the hash table dynamically allocates a bucket array of double size (typically a prime number) and rehashes all active entries to maintain average O(1) time complexity.

🧭 4. Graph Traversals & Dijkstra's Shortest Path Algorithm

Network Topology • Greedy Relaxation

Graphs represent networks of entities (vertices V) connected by relationships (edges E). They are computationally modeled as either an Adjacency Matrix (an |V| × |V| matrix with O(1) edge lookup and O(V²) space) or an Adjacency List (an array of lists with O(deg(V)) edge lookup and optimal O(V + E) space).

A. Breadth-First Search (BFS) vs. Depth-First Search (DFS)

Attribute Breadth-First Search (BFS) Depth-First Search (DFS)
Primary Data Structure FIFO Queue (Iterative) Call Stack (Recursion) or Explicit LIFO Stack
Traversal Pattern Concentric rings / level-by-level outwards Plunges along branch paths until reaching a dead end
Time Complexity O(V + E) O(V + E)
Space Complexity O(V) (queue holds maximum tier width) O(V) (call stack bounded by graph diameter / depth)
Core Use Cases Shortest path in unweighted graphs, peer-to-peer discovery Cycle detection, Topological sort, Connected components

B. Dijkstra's Shortest Path Algorithm & Edge Relaxation

Dijkstra's algorithm finds the shortest path from a starting source vertex to every other vertex in a weighted graph with non-negative edge weights (w(u, v) ≥ 0). It operates greedily by maintaining an array of provisional shortest distances dist[] initialized to ∞ (with dist[source] = 0) and a Min-Priority Queue of vertices keyed on their current distance.

The Relaxation Invariant: For an edge (u, v) with weight w:
if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; parent[v] = u; }
Relaxation checks if traveling through node u provides a shorter cumulative path to v than previously known.

Asymptotic Time Complexity: Using a Fibonacci Heap, Dijkstra runs in O(E + V log V). With standard binary min-heaps, it runs in O((V + E) log V).
Important Note: Dijkstra fails on graphs containing negative weight cycles because its greedy assumption—that once a node is settled its shortest path cannot be reduced—is invalidated (use the Bellman-Ford algorithm for negative edge weights).

⚡ 5. Sorting Algorithm Benchmark & Asymptotic Complexity Matrix

Empirical Analysis • Stability & Memory

Sorting algorithms reorder an array into monotonic sequence. Algorithm selection in production systems (e.g. Timsort in Python/Java, Introsort in C++ STL) depends on array size, stability requirements, cache locality, and whether the data is partially presorted.

Algorithm Best Time Average Time Worst Time Space Complexity Stable? In-Place?
Bubble Sort O(N) (with swap flag) O(N²) O(N²) O(1) Yes Yes
Selection Sort O(N²) O(N²) O(N²) O(1) No Yes
Insertion Sort O(N) (nearly sorted) O(N²) O(N²) O(1) Yes Yes
Merge Sort O(N log N) O(N log N) O(N log N) O(N) Yes No
Quick Sort O(N log N) O(N log N) O(N²) (bad pivot) O(log N) (call stack) No Yes
Heap Sort O(N log N) O(N log N) O(N log N) O(1) No Yes
Stability Definition: A sorting algorithm is stable if two items with identical comparison keys appear in the output array in the exact same relative order as they were in the original input. This is critical when sorting multi-attribute records (e.g. sorting students by age, then preserving order when sorting by department).