Comprehensive Study Notes: Data Structures and Algorithms

Foundations of Algorithms and Pseudocode Implementations

  • Methodology and Scope:

    • The provided material focuses on language-independent implementations of common and uncommon algorithms using pseudocode. This approach allows for easy porting to most imperative programming languages.

    • The implementations represent designs by the authors based on core concepts; they may differ from standard library implementations or normalization seen in other texts.

    • Algorithm analysis is conducted using abstract Big Oh notation to assess run time complexity, appealing to a broad audience without requiring formal mathematical proofs for every instance. It is recommended to use this material alongside texts containing formal proofs.

  • Assumed Knowledge:

    • Big Oh Notation: Essential for determining the best algorithm for specific scenarios based on run time complexity.

    • Imperative Programming: Proficiency in languages such as C++C++, C#C\#, or Java is required to port the pseudo-imperative code. Functional programmers (Haskell, F#, OCaml) must adapt these logic patterns to the functional paradigm.

    • Object-Oriented (OO) Concepts: Understanding of inheritance, encapsulation, and polymorphism is necessary to appreciate the design of the data structures.

    • Virtual Machines: C# and Java target virtual machines providing garbage collection and security sandboxing. When porting to C++C++, references in pseudocode should be interpreted as pointers.

Big Oh Notation and Complexity Analysis

  • Growth as a Key Factor: Big Oh isolates growth as the primary factor in algorithm analysis, allowing for hardware-independent comparisons. A logarithmic algorithm will eventually outperform a quadratic algorithm as n→∞n \rightarrow \infty, regardless of the machine's speed.

  • Common Complexity Classes:

    • O(1)O(1) (Constant): Operations independent of input size, such as adding a node to the tail of a linked list with a tail pointer.

    • O(log⁡(n))O(\log(n)) (Logarithmic): Algorithms that divide the problem into smaller chunks per invocation, such as searching a Binary Search Tree (BST).

    • O(n)O(n) (Linear): Run time is directly proportionate to input size nn.

    • O(nlog⁡(n))O(n \log(n)) (n log n): Algorithms that split problems into chunks and then stitch the results back together, such as Quick Sort.

    • O(n2)O(n^2) (Quadratic): Often seen in algorithms with nested loops, like Bubble Sort.

    • O(n3)O(n^3) (Cubic) and O(2n)O(2^n) (Exponential): Extremely rare and highly inefficient. They should be avoided or reserved for very small problems. Enountering these should trigger a design review.

Pseudocode Standards and Conventions

  • Algorithm Structure:

    • All algorithms start with a signature: algorithm AlgorithmName(arg1, arg2, ..., argN) and end with end AlgorithmName.

    • Scope for loops and conditionals is explicitly closed (e.g., end if, end for, end while) to prevent ambiguity.

  • Contractual Conditions:

    • Pre-conditions: Requirements that must be met before execution (e.g., n≥0n \ge 0 or parameters not being null). These are critical to algorithm operation.

    • Post-conditions: The state of the data or the result returned after the algorithm concludes (e.g., "The list has been sorted").

  • Parameter Inference:

    • Types are inferred from context. Variable nn usually denotes an integer equivalent to a WORD on a 32-bit machine. Variable ll often denotes a list or resizable array.

  • Keywords:

    • yield: Used similarly to return, but it returns each value to the caller sequentially. Control returns to the caller only when all values are exhausted.

Linked Lists

  • Structural Properties: Linked lists consist of a series of nodes where each node contains a value and at least one pointer/reference to another node.

    • Head and Tail Pointers: Maintaining both head and tail pointers allows for O(1)O(1) insertion at both ends.

    • Singly Linked List: Each node has a Value and a Next reference.

    • Doubly Linked List: Each node has Value, Next, and Previous references.

  • Complexity Summary:

    • Insertion: O(1)O(1) for head or tail. For random insertion (middle of the list), the complexity is O(n)O(n) due to the need to traverse to the predecessor.

    • Deletion: O(n)O(n) in general, as the node must be found. If deleting specifically from the head, it is O(1)O(1).

    • Searching: Always O(n)O(n).

  • Traversal Techniques:

    • Forward Traversal: Start at the head and follow Next pointers until reaching ∅\emptyset.

    • Singly Linked Reverse Traversal: Highly inefficient (O(n2)O(n^2)) because finding a predecessor for each node requires an O(n)O(n) scan from the head.

    • Doubly Linked Reverse Traversal: Efficiently performed by starting at the tail and following Previous pointers.

Binary Search Trees (BST)

  • Organizational Rule: For a root node with value xx, the left subtree contains values <x< x and the right subtree contains values ≥x\ge x.

  • Complexity: If the tree is reasonably balanced, Insert, Lookup, and Deletion are O(log⁡(n))O(\log(n)). A pathologically unbalanced tree becomes a linked list with O(n)O(n) complexity.

  • Traversal Strategies:

    • Preorder: Visit root, then left subtree, then right subtree.

    • Postorder: Visit left subtree, then right subtree, then root.

    • Inorder: Visit left subtree, then root, then right subtree. This yields values in their sorted comparison order.

    • Breadth-First: Visit all nodes at a specific depth dd from left to right before moving to depth d+1d+1. Usually implemented using a queue.

Heaps

  • Definition: A tree-based structure generally implemented as an array. Heaps follow specific ordering strategies:

    • Min-Heap: The parent node's value is ≤\le its children's values. The root is the minimum.

    • Max-Heap: The parent node's value is ≥\ge its children's values. The root is the maximum.

  • Array Mapping for Index ii:

    • Parent Index: i−12\frac{i - 1}{2}

    • Left Child: 2×i+12 \times i + 1

    • Right Child: 2×i+22 \times i + 2

  • Operations:

    • Insert (O(log⁡(n))O(\log(n))): Add the value to the first free slot and invoke MinHeapify (or MaxHeapify) to bubble the value up and restore order.

    • Remove (O(log⁡(n))O(\log(n))): Find the target, replace it with the last element in the array, and then bubble that element down to restore order.

    • Search (O(n)O(n)): Involves a sequential scan of the array. Optimizations for Contains can use the heap property to stop early if the target value falls outside the range of a level (value>Parent(n)value > Parent(n) and value<nvalue < n for all nn at level ii).

Sets

  • General Properties: Collections of unique, distinct values with no defined order. Notation: A={4,7,9}A = \{4, 7, 9\}. Membership: 4∈A4 \in A.

  • Standard Operations:

    • Union (A∪BA \cup B): Every element in AA or BB. Complexity: O(m+n)O(m + n).

    • Intersection (A∩BA \cap B): Elements present in both AA and BB. Complexity: O(n)O(n) where nn is the size of the smaller set.

  • Implementation Types:

    • Unordered Set: Backed by a Hash Table. Provides near O(1)O(1) insertion and lookup.

    • Ordered Set: Backed by a balanced tree like an AVL tree. Provides O(log⁡(n))O(\log(n)) insertion and lookup, maintaining sorted order via inorder traversal.

Queues

  • First-In-First-Out (FIFO): The first item added is the first served.

  • Core Methods:

    • Enqueue: Place item at the back.

    • Dequeue: Remove and return the front item.

    • Peek (or Front): Return front item without removal.

  • Variations:

    • Standard Queue: Efficiently implemented with a singly linked list (O(1)O(1) enqueue/dequeue).

    • Priority Queue: Items ordered by a comparer. Best implemented with a Heap; looking at the highest priority item is an O(1)O(1) check of index 0.

    • Double Ended Queue (Deque): Allows access to both front and back. Usually implemented with a doubly linked list to avoid O(n)O(n) array resizing costs.

AVL Trees

  • Self-Balancing Property: Invented by Adelson-Velsky and Landis. The height difference (Balance Factor) between left and right subtrees of any node is at most 11. This ensures O(log⁡(n))O(\log(n)) height.

  • Tree Rotations (O(1)O(1)): Constant-time operations to restore balance by moving subtrees up or down.

    • Left Rotation: Triggered when a right subtree is too heavy.

    • Right Rotation: Triggered when a left subtree is too heavy.

    • Double Rotations: LeftAndRightRotation and RightAndLeftRotation handle cases where a single rotation is insufficient.

Sorting Algorithms

  • Bubble Sort (O(n2)O(n^2)): Repeatedly compares and swaps adjacent elements.

  • Merge Sort (O(nlog⁡(n))O(n \log(n))): A divide-and-conquer algorithm. Splits the list until size 1, then merges sorted sub-lists using a MergeOrdered helper.

  • Quick Sort (O(nlog⁡(n))O(n \log(n))): Uses a pivot to partition the list into less, equal, and greater sub-lists. Median-value pivot selection is ideal to avoid O(n2)O(n^2) worst-case performance.

  • Insertion Sort (O(n2)O(n^2)): Builds a sorted sequence one item at a time, similar to sorting a hand of playing cards.

  • Shell Sort (O(nlog⁡2(n))O(n \log^2(n))): A variation of insertion sort that compares items at varying distances (increments).

  • Radix Sort: Uses buckets (queues) to sort items by individual digits (keys). Requires isolating keys: key←(number/keyToAccess)(mod10)key \leftarrow (number / keyToAccess) \pmod{10}.

Numeric Algorithms

  • Primality Test: Checks if nn is prime by iterating from 22 up to n\sqrt{n}.

  • Greatest Common Denominator (GCD): Euclid's algorithm used to find the largest multiple of two integers using recursion: GreatestCommonDenominator(n, m % n).

  • Base Max Value: The maximum value for a base BB with NN digits is calculated as BN−1B^N - 1.

    • Example: Hexademical (Base 16) with 6 digits is 166−1=1677721516^6 - 1 = 16777215 (FFFFFF16FFFFFF_{16}).

  • Factorial (N!N!): Iterative implementation is preferred over recursive to avoid overhead. 0!=10! = 1. For n≥2n \ge 2, factorial←factorial×ifactorial \leftarrow factorial \times i.

Searching Algorithms

  • Sequential Search (O(n)O(n)): Basic linear loop through a list.

  • Probability Search (O(n)O(n)): A variation of sequential search that swaps a found item with its predecessor. This increases the probability that frequently accessed items move to the front of the list, reducing average scan time.

String Algorithms

  • Reverse Words: Uses a string buffer to rebuild the sentence by identifying word boundaries (white space) and marching backwards from the end of the string.

  • Palindrome Detection (O(n)O(n)): Uses two pointers at the left and right ends of a stripped, uppercase string. Pointers move inward as long as characters match.

  • Word Counting: Uses a Boolean flag inWord to track the state transitions between white space and characters to handle multiple spaces between words.

  • Repeated Word Count: Splits a string into an array, adds each stripped word to a Set, and subtracts the Set's total count from the array's total length.

  • Any Character Match (O(n2)O(n^2)): Determines if any character in one string exists in another using a nested double loop.

Practical Implementation Tips

  • Verification: Work through algorithms manually with pen and paper using a variable mutation table to track state change.

  • Recursion Warning: Use recursion for tree structures but be cautious of overhead in linear or quadratic logic.

  • Memory Management: In managed languages (C#C\#, Java), nullify references in data structures (like Heaps) after deletion so the garbage collector can reclaim memory.