Comprehensive Study Guide on Data Structures, Algorithms, Complexity Analysis, and Stack Implementations

Course Overview & Administrative Details

  • Course Identification: CSC 290, taught by Dr. Timothy Highley at La Salle University.

  • Academic Support & Tutoring:

    • Tutoring Location: Holroyd 166.

    • Tutoring Schedule: Tuesday 2:30–3:30 PM; Thursday 12:30–1:30 PM.

    • Instructor Office Hours: Monday 2:00–3:00 PM; Tuesday/Friday 10:00–11:00 AM.

  • Notable Quotes:

    • Thomas Sowell: "It is hard to imagine a more stupid or more dangerous way of making decisions than by putting those decisions in the hands of people who pay no price for being wrong."

    • Sarah Sparks (from "Into the Lantern Waste"): "So you might turn the page or you might shut the book, but the truth is still truth even if you don’t look."

    • Benjamin Franklin: "Well done is better than well said."

    • Yogi Berra: "You got to be careful if you don't know where you're going, because you might not get there."

    • C. A. R. Hoare: "There are two ways of constructing a software design; one way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult."

Computer Architecture & Memory Fundamentals

  • Hardware Components:

    • CPU (Central Processing Unit): The primary execution unit responsible for performing computations and running instruction sets.

    • RAM (Random Access Memory): Also known as main memory or simply memory. Program execution requires loading code and working data directly into RAM.

    • I/O (Input/Output): All peripherals and secondary storage devices outside the CPU and RAM, including keyboards, monitors, hard drives, network cards, and printers.

  • RAM Structure & Memory Addressing:

    • Conceptually structured as one contiguous, massive array.

    • A memory address functions precisely as an index into this primary array.

  • Pointers vs. Java References:

    • Pointer: A variable that directly stores a physical or virtual RAM address.

    • Java Reference: An abstract encapsulation of a memory address. Java conceals the direct numeric address from the programmer; references can only be dereferenced to manipulate or retrieve the targeted object.

Algorithm Analysis & Asymptotic Complexity

  • Fundamental Objective:

    • Determine execution runtime as a function of input size nn.

    • Inputs vary based on problem domains (e.g., number of elements in a search space or length of an array to sort).

    • Measuring exact execution time is impractical due to hardware variation; analysis counts high-level operational growth instead.

  • Asymptotic Complexity & Order of Growth:

    • Evaluates performance behavior as input size nn grows arbitrarily large (n→∞n \rightarrow \text{∞}).

    • Dominant terms dictate long-term growth; lower-order terms and multiplicative constants become insignificant and are omitted.

    • Comparison Example: Consider f(n)=3n2f(n) = 3n^2 and g(n)=10n2+12000n+1000g(n) = 10n^2 + 12000n + 1000. Although g(n)g(n) has large lower-order coefficients, both functions share the dominant term n2n^2 and display identical asymptotic growth rates.

  • Standard Big-O Reference Functions (Ordered from Fastest to Slowest):

    • Constant Time: O(1)O(1)

    • Logarithmic Time: O(log⁡(n))O(\log(n))

    • Linear Time: O(n)O(n)

    • Linearithmic Time: O(nlog⁡(n))O(n \log(n))

    • Quadratic Time: O(n2)O(n^2)

    • Exponential Time: O(2n)O(2^n)

    • Factorial Time: O(n!)O(n!)

  • Mathematical Properties & Worst-Case Analysis:

    • Upper Bound Definition: Big-O establishes a formal mathematical upper bound. An algorithm that is O(1)O(1) is technically also O(n)O(n) and O(n2)O(n^2), though the tightest bound is always preferred.

    • Conditional Statements: Evaluated by identifying the worst-case (slowest) execution path among all conditional branches.

    • Why Worst-Case Analysis?

    • Best-Case: Too optimistic to provide practical guarantees.

    • Average-Case: Requires complex mathematical modeling and complete statistical knowledge of input distributions.

    • Worst-Case: Provides absolute performance guarantees and accurately reflects real-world computational bottlenecks.

  • Rules for Structural Loop Analysis:

    • Single Loops: Executing nn times yields O(n)O(n).

    • Nested Loops: Multiply iteration counts across nested levels. Inner loops running a fixed constant number of times (e.g., 1000 iterations regardless of nn) evaluate to O(1)O(1) multiplicative factors and drop out.

    • Logarithmic Loops: A loop variable that multiplies or divides by a factor on each iteration (e.g., count2 = count2 * 2) runs in O(log⁡(n))O(\log(n)) time.

    • Method Calls Inside Loops: The total complexity equals the outer loop iterations multiplied by the asymptotic complexity of the called method. Method overhead (stack frame setup, parameter passing) is treated as O(1)O(1) constant overhead.

  • Analysis of Code Snippets:

    • Snippet 1: Nested loop with step size 2. java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2 = count2 + 2) System.out.println("hi"); &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: Outer loop runs nn times; inner loop runs n2\frac{n}{2} times. Result: O(n2)O(n^2).

    • Snippet 2: Nested loop with logarithmic inner step. java for (int count = 0; count < n; count++) for (int count2 = 1; count2 < n; count2 = count2 * 2) System.out.println("hi"); &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: Outer loop runs nn times; inner loop runs log⁡2(n)\log_2(n) times. Result: O(nlog⁡(n))O(n \log(n)).

    • Snippet 3: Outer linear loop with fixed inner constant loop. java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < 1000; count2++) System.out.println("hi"); &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: Outer loop runs nn times; inner loop runs 1000 times (constant). Result: O(n)O(n).

    • Snippet 4: Triple nested linear loops. java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2++) for (int count3 = 0; count3 < n; count3++) System.out.println("hi"); &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: Three nested loops running nn times each (n×n×nn \times n \times n). Result: O(n3)O(n^3).

    • Snippet 5: Nested linear loop invoking O(n)O(n) method. java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2++) methodA(n); // methodA is O(n) &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: n×n×O(n)n \times n \times O(n). Result: O(n3)O(n^3).

    • Snippet 6: Constant inner loop invoking O(n2)O(n^2) method. java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < 1000; count2++) methodA(n); // methodA is O(n^2) &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: n×1000×O(n2)n \times 1000 \times O(n^2). Result: O(n3)O(n^3).

    • Snippet 7: Nested linear loop invoking O(n2)O(n^2) method. java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2++) methodA(n); // methodA is O(n^2) &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: n×n×O(n2)n \times n \times O(n^2). Result: O(n4)O(n^4).

    • Snippet 8: Constant inner loop invoking O(nlog⁡(n))O(n \log(n)) method. java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < 1000; count2++) methodA(n); // methodA is O(n log n) &nbsp;&nbsp;&nbsp;&nbsp;     Complexity: n×1000×O(nlog⁡(n))n \times 1000 \times O(n \log(n)). Result: O(n \log(n))$.\n - *Snippet 9:* Constant method parameter.\n ```java\n for (int count = 0; count < n; count++)\n for (int count2 = 0; count2 < 1000; count2++)\n methodA(50); // methodA is O(n log n)\n    ```\n    *Complexity:* Since parameter 50 is a constant, `methodA(50)` evaluates to O(1)workrelativetovariableinputsizework relative to variable input sizen.Result:. Result:O(n).\n- **Simplification Practice Problems:**\n - 10n^2 + 100 \rightarrow O(n^2)\n - 100n^2 \log(n) \rightarrow O(n^2 \log(n))\n - 50 \log(n) \rightarrow O(\log(n))\n - 30n^3 + 20n^2 + 10 \rightarrow O(n^3)\n - n^2 + 2^n \rightarrow O(2^n)\n - 1000 \rightarrow O(1)\n - 2^n + 100n^3 \rightarrow O(2^n)\n - 5n^4 + 11n^2 + 150 \rightarrow O(n^4)\n - 80n + 15 \rightarrow O(n)\n - 140n^3 \log(n) + 5n^2 \rightarrow O(n^3 \log(n))\n - 14n^3 + 2^n \rightarrow O(2^n)\n - 12 \rightarrow O(1)\n - 2^n + 310n^2 \rightarrow O(2^n)\n - 11 \log_2(n) + 30 \log(n) \rightarrow O(\log(n))\n- **Space Complexity:**\n - Measures memory space required by an algorithm as a function of input size n$$.

Classic Sorting Algorithms

  • Selection Sort:

    • Iteratively scans the unsorted portion of a list to select the specific element that belongs in the next available index.

    • Placed elements remain fixed in position.

  • Insertion Sort:

    • Maintains a sorted sublist at the front of the collection.

    • Iteratively takes the next unsorted element and inserts it into its correct relative position within the sorted section.

Java Collections Framework Overview

  • Enhanced For Loop ("for-each"):

    • Syntax: for (ElementType var : collection)

    • Iterates sequentially through arrays or any class implementing the generic Iterable<T> interface.

  • LinkedList Class (java.util.LinkedList):

    • Implements generic linear data structures.

    • Essential Methods: add(), get(), set(), size(), remove(int index) (remove by position), remove(Object o) (remove first matching element).

  • ListIterator Interface (java.util.ListIterator):

    • Enables bidirectional traversal and dynamic modification of list structures.

    • Traversal & Index Methods: next(), nextIndex(), previous(), previousIndex(), hasNext(), hasPrevious().

    • Modification Methods: add(), remove(), set().

  • Map Interface (java.util.Map):

    • Stores associations between unique keys and corresponding values.

    • Key/Value types can be any object class. Keys can be integers to emulate dynamic array behavior.

    • Key Methods: put(K key, V value) (inserts or updates key mapping), containsKey(Object key) (returns boolean), get(Object key) (retrieves mapping or null), remove(Object key) (deletes key-value pair).

  • Queue Interface (java.util.Queue):

    • Abstract Data Type following First-In, First-Out (FIFO) semantics.

    • Standard Operations: Enqueue (add), Dequeue (remove front), Peek (examine front).

    • Java Implementation Class: Typically instantiated via LinkedList.

    • Object Instantiation Example: java Queue<String> myQueue = new LinkedList<String>(); &nbsp;&nbsp;&nbsp;&nbsp;

    • Operations & Exceptions Table:

    • Enqueue: add()

    • Dequeue: remove() (throws NoSuchElementException if empty), poll() (returns null if empty)

    • Peek: element() (throws NoSuchElementException if empty), peek() (returns null if empty)

  • Deque Interface (java.util.Deque):

    • Stands for "double-ended queue" (pronounced "deck").

    • Supports element insertion, inspection, and removal at both ends.

    • Java Implementation Class: Instantiated via LinkedList.

    • Object Instantiation Example: java Deque<Integer> myDeque = new LinkedList<Integer>(); &nbsp;&nbsp;&nbsp;&nbsp;

    • Method Operations Summary:

    • Insertion: addFirst(), addLast()

    • Removal (Exception-throwing): removeFirst(), removeLast()

    • Removal (Null-returning): pollFirst(), pollLast()

    • Inspection (Exception-throwing): getFirst(), getLast()

    • Inspection (Null-returning): peekFirst(), peekLast()

Stacks Abstract Data Type

Stack of cardboard boxes illustrating top-end additions and removals
  • Definition & Fundamentals:

    • A stack is a linear collection whose elements are added and removed exclusively from a single end, defined as the top of the stack.

    • Operates on Last-In, First-Out (LIFO) order: the most recently added element is always the first to be extracted.

    • Direct access to elements beneath the top is strictly prohibited.

  • Classic Stack Operations:

    • push: Inserts a new element onto the top of the stack.

    • pop: Removes and returns the element currently at the top.

    • peek: Returns the top element without modifying the stack state.

    • isEmpty / empty: Returns a boolean indicating whether the stack contains zero elements.

Diagram illustrating push operation adding an element to a stack
  • Complete Operational Walkthrough:

    • Executing a sequential series of stack operations traces as follows:

Visual representation of stack state transitions during push and pop operations
  1. push(A) → Stack state: [A] (Top: A)

  2. push(B) → Stack state: [A, B] (Top: B)

  3. push(C) → Stack state: [A, B, C] (Top: C)

  4. push(D) → Stack state: [A, B, C, D] (Top: D)

  5. pop() → Removes D, Stack state: [A, B, C] (Top: C)

  6. pop() → Removes C, Stack state: [A, B] (Top: B)

  7. push(E) → Stack state: [A, B, E] (Top: E)

  8. push(F) → Stack state: [A, B, E, F] (Top: F)

  9. push(G) → Stack state: [A, B, E, F, G] (Top: G)

  10. pop() → Removes G, Stack state: [A, B, E, F] (Top: F)

  11. pop() → Removes F, Stack state: [A, B, E] (Top: E)

  • Real-World Application: Runtime Call Stack:

    • Computer runtime environments utilize a call stack to track nested method invocation chains.

    • Calling a method pushes an activation record (stack frame) containing local variables, parameters, and return addresses onto the call stack.

    • Completing method execution pops its activation record, returning control to the caller method directly underneath.

Architectural Flaws of java.util.Stack

Jenga tower illustrating illegal removal of elements from the middle of a stack
  • Standard Library Class Overview:

    • The Java API provides java.util.Stack<E> which utilizes generic typing: java Stack<Book> bookStack = new Stack<Book>(); Stack<String> nameStack = new Stack<String>(); &nbsp;&nbsp;&nbsp;&nbsp;

    • Built-in Methods: push(E item), pop(), peek(), empty(). Invoking pop() or peek() on an empty stack throws java.util.EmptyStackException.

  • Design Deficiencies:

    • java.util.Stack was introduced in Java 1.0 and directly extends java.util.Vector.

    • Because Vector is a random-access positional list, java.util.Stack inherits public methods that allow non-LIFO modifications:

    • remove(int index) → Deletes arbitrary elements anywhere in the stack.

    • insertElementAt(E obj, int index) → Inserts elements directly into the middle or bottom.

    • get(int index) / set(int index, E element) → Reads and modifies arbitrary entries.

    • Inheriting positional list operations breaks the fundamental abstraction of a stack.

Meme illustrating the design flaw of java.util.Stack inheriting from Vector

Custom Stack Interface Specification

  • To enforce clean encapsulation and prevent access violations, a explicit custom interface is defined:

public interface Stack<T> {
    public void push(T element);
    public T pop();
    public T peek();
    public boolean isEmpty();
    public int size();
    public String toString();
}

Algorithm Case Study: Parentheses Matching

  • Problem Definition:

    • Parse an arithmetic expression string and verify whether all left parentheses ( correctly pair with matching right parentheses ).

  • State Encapsulation:

    • Defined via the MatchState enum: java public enum MatchState { BALANCED, MISSING_LEFT, MISSING_RIGHT } &nbsp;&nbsp;&nbsp;&nbsp;

  • Class Implementation:

  public class MatchingParentheses {
      private String expression;
      private Stack<Character> stack;

      public MatchingParentheses(String expression) {
          this.expression = expression;
          this.stack = new Stack<Character>();
      }

      public MatchState check() {
          for (int i = 0; i < expression.length(); i++) {
              Character paren = expression.charAt(i);
              if (!checkParen(paren))
                  return MatchState.MISSING_LEFT;
          }
          if (stack.empty())
              return MatchState.BALANCED;
          else
              return MatchState.MISSING_RIGHT;
      }

      private boolean checkParen(Character ch) {
          if (ch == '(')
              stack.push(ch);
          else if (ch == ')' && (stack.empty() || stack.pop() != '('))
              return false;
          return true;
      }
  }
&nbsp;&nbsp;```
- **Operational Logic:**
  - Scanning encountered `(` characters pushes them onto the stack.
  - Encountering a `)` causes an evaluation: if the stack is empty or popping the top element does not yield `(`, `checkParen` returns `false` (signaling `MISSING_LEFT`).
  - After full expression traversal, if the stack is completely empty, it returns `BALANCED`; otherwise, unclosed opening parentheses remain, returning `MISSING_RIGHT`.
- **Console Driver Execution Tracing:**

java System.out.print("Enter math expression (q to quit): "); String expression = in.nextLine(); MatchingParentheses.MatchState state = matcher.check();

if (state == MatchingParentheses.MatchState.MISSING_RIGHT) System.out.println("Missing right parenthesis"); else if (state == MatchingParentheses.MatchState.MISSING_LEFT) System.out.println("Missing left parenthesis"); else System.out.println("Parentheses are balanced");   ```

  • Sample Run Outputs:

    • Input: (5+4) → Output: Parentheses are balanced

    • Input: ((9*2) → Output: Missing right parenthesis

    • Input: 7) → Output: Missing left parenthesis

    • Input: q → Output: Done checking

Array-Based Stack Implementation (ArrayStack)

Stacked colored storage boxes
  • Internal Representation:

    • Stores elements inside a continuous array using dynamic array resizing.

    • Maintains an integer top that tracks the array index of the current top element. An empty stack is represented by top = -1.

Array implementation of a stack showing indices and element references
  • Complete Source Code Implementation:

  import java.util.Arrays;
  import java.util.EmptyStackException;

  public class ArrayStack<T> implements Stack<T> {
      private final static int DEFAULT_CAPACITY = 20;
      private int top;
      private T[] stack;

      public ArrayStack() {
          this(DEFAULT_CAPACITY);
      }

      @SuppressWarnings("unchecked")
      public ArrayStack(int initialCapacity) {
          top = -1;
          stack = (T[])(new Object[initialCapacity]);
      }

      public void push(T element) {
          if (size() == stack.length)
              stack = Arrays.copyOf(stack, stack.length * 2);
          top++;
          stack[top] = element;
      }

      public T pop() throws EmptyStackException {
          if (isEmpty())
              throw new EmptyStackException();
          T result = stack[top];
          stack[top] = null;
          top--;
          return result;
      }

      public T peek() throws EmptyStackException {
          if (isEmpty())
              throw new EmptyStackException();
          return stack[top];
      }

      public boolean isEmpty() {
          return top == -1;
      }

      public int size() {
          return top + 1;
      }

      public String toString() {
          String description;
          if (isEmpty())
              description = "The stack is empty.";
          else {
              description = "There are " + size() + " elements in the stack:
";
              for (int i = top; i >= 0; i--)
                  description += stack[i] + "
";
          }
          return description;
      }
  }
&nbsp;&nbsp;```
- **Execution Driver & Output Tracing:**

java Stack myStack = new ArrayStack(); System.out.println(myStack);

myStack.push("uno"); myStack.push("dos"); myStack.push("tres"); System.out.println(myStack);

myStack.pop(); System.out.println(myStack);   ```

Console output of ArrayStackDemo showing stack state after push and pop
  • Terminal Output Produced: ```text The stack is empty.

    There are 3 elements in the stack: tres dos uno

    There are 2 elements in the stack: dos uno     ```

Linked-List Stack Implementation (LinkedStack)

Stack of ceramic plates representing a linked stack structure
  • Internal Structural Design:

    • Employs a singly-linked list node chain where insertions and removals occur at the head node (top).

    • Avoids array capacity limits and removes the need for resizing operations.

Linked list structure representing a stack with nodes and next pointers
  • Node Encapsulation:

    • Uses a private inner class Node to encapsulate payload data (elem) and the link reference (next).

Diagram showing Node class encapsulated as an inner class within LinkedStack
  • Complete Source Code Implementation:

  import java.util.EmptyStackException;

  public class LinkedStack<T> implements Stack<T> {
      private Node top;
      private int count;

      public LinkedStack() {
          top = null;
          count = 0;
      }

      public void push(T element) {
          top = new Node(element, top);
          count++;
      }

      public T pop() throws EmptyStackException {
          if (isEmpty())
              throw new EmptyStackException();
          T element = top.elem;
          top = top.next;
          count--;
          return element;
      }

      public T peek() throws EmptyStackException {
          if (isEmpty())
              throw new EmptyStackException();
          return top.elem;
      }

      public boolean isEmpty() {
          return top == null;
      }

      public int size() {
          return count;
      }

      public String toString() {
          String description;
          if (isEmpty())
              description = "The stack is empty.
";
          else {
              if (size() == 1)
                  description = "1 element in stack:
";
              else
                  description = size() + " elements in stack:
";

              Node current = top;
              while (current != null) {
                  description += current.elem + "
";
                  current = current.next;
              }
          }
          return description;
      }

      private class Node {
          private T elem;
          private Node next;

          public Node(T element) {
              this(element, null);
          }

          public Node(T element, Node next) {
              this.elem = element;
              this.next = next;
          }
      }
  }
&nbsp;&nbsp;```
- **Demo Driver Integration:**

java public class LinkedStackDemo { public static void main(String[] args) { Stack myStack = new LinkedStack(); System.out.println(myStack);

      myStack.push("Lucy");
      System.out.println(myStack);

      myStack.push("Ricky");
      myStack.push("Fred");
      myStack.push("Ethel");
      System.out.println(myStack);
  }

}   ```