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 .
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 grows arbitrarily large ().
Dominant terms dictate long-term growth; lower-order terms and multiplicative constants become insignificant and are omitted.
Comparison Example: Consider and . Although has large lower-order coefficients, both functions share the dominant term and display identical asymptotic growth rates.
Standard Big-O Reference Functions (Ordered from Fastest to Slowest):
Constant Time:
Logarithmic Time:
Linear Time:
Linearithmic Time:
Quadratic Time:
Exponential Time:
Factorial Time:
Mathematical Properties & Worst-Case Analysis:
Upper Bound Definition: Big-O establishes a formal mathematical upper bound. An algorithm that is is technically also and , 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 times yields .
Nested Loops: Multiply iteration counts across nested levels. Inner loops running a fixed constant number of times (e.g., 1000 iterations regardless of ) evaluate to 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 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 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"); Complexity: Outer loop runs times; inner loop runs times. Result: .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"); Complexity: Outer loop runs times; inner loop runs times. Result: .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"); Complexity: Outer loop runs times; inner loop runs 1000 times (constant). Result: .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"); Complexity: Three nested loops running times each (). Result: .Snippet 5: Nested linear loop invoking method.
java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2++) methodA(n); // methodA is O(n) Complexity: . Result: .Snippet 6: Constant inner loop invoking method.
java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < 1000; count2++) methodA(n); // methodA is O(n^2) Complexity: . Result: .Snippet 7: Nested linear loop invoking method.
java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2++) methodA(n); // methodA is O(n^2) Complexity: . Result: .Snippet 8: Constant inner loop invoking method.
java for (int count = 0; count < n; count++) for (int count2 = 0; count2 < 1000; count2++) methodA(n); // methodA is O(n log n) Complexity: . 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)nO(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>(); Operations & Exceptions Table:
Enqueue:
add()Dequeue:
remove()(throwsNoSuchElementExceptionif empty),poll()(returnsnullif empty)Peek:
element()(throwsNoSuchElementExceptionif empty),peek()(returnsnullif 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>(); 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

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.

Complete Operational Walkthrough:
Executing a sequential series of stack operations traces as follows:

push(A)→ Stack state:[A](Top: A)push(B)→ Stack state:[A, B](Top: B)push(C)→ Stack state:[A, B, C](Top: C)push(D)→ Stack state:[A, B, C, D](Top: D)pop()→ Removes D, Stack state:[A, B, C](Top: C)pop()→ Removes C, Stack state:[A, B](Top: B)push(E)→ Stack state:[A, B, E](Top: E)push(F)→ Stack state:[A, B, E, F](Top: F)push(G)→ Stack state:[A, B, E, F, G](Top: G)pop()→ Removes G, Stack state:[A, B, E, F](Top: F)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

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>(); Built-in Methods:
push(E item),pop(),peek(),empty(). Invokingpop()orpeek()on an empty stack throwsjava.util.EmptyStackException.
Design Deficiencies:
java.util.Stackwas introduced in Java 1.0 and directly extendsjava.util.Vector.Because
Vectoris a random-access positional list,java.util.Stackinherits 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.

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
MatchStateenum:java public enum MatchState { BALANCED, MISSING_LEFT, MISSING_RIGHT }
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;
}
}
```
- **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 balancedInput:
((9*2)→ Output:Missing right parenthesisInput:
7)→ Output:Missing left parenthesisInput:
q→ Output:Done checking
Array-Based Stack Implementation (ArrayStack)

Internal Representation:
Stores elements inside a continuous array using dynamic array resizing.
Maintains an integer
topthat tracks the array index of the current top element. An empty stack is represented bytop = -1.

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;
}
}
```
- **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); ```

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)

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.

Node Encapsulation:
Uses a private inner class
Nodeto encapsulate payload data (elem) and the link reference (next).

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;
}
}
}
```
- **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);
}
} ```