Data Structures and Algorithms Study Guide
Foundations of Data Structures and Algorithms
Data Structures and Algorithms (DSA) provide the foundational principles required to organize data efficiently and write optimal software applications. Understanding DSA allows developers to minimize resource consumption during search, sort, and write operations.
Prerequisites for studying DSA include:
Basic proficiency in a programming language, including conditional statements, loops, methods/functions, arrays/collections, and Object-Oriented Programming (OOP) concepts.
An Integrated Development Environment (IDE) compatible with the chosen programming language.
The study of DSA combines two complementary perspectives:
Theories and Algorithms: Conceptual analysis applied to real-life scenarios to observe data flow and internal logic.
Implementation: Practical coding using specific programming languages to build and manage data structures.
Key Definitions:
Data: A raw, unorganized collection of numbers, symbols, or characters.
Information: Data that has been organized, processed, and structured in a meaningful format.
Data Structure: A specialized format for organizing, managing, and storing data on a device to facilitate efficient access and modification.
Algorithm: A finite sequence of clear instructions designed to perform a specific task or solve a computational problem.
Real-World Analogies of Data Organization:
Dictionary: Entries are stored alphabetically to enable rapid, structured lookup.
Supermarket / Grocery Store: Products are organized categorically by aisle (such as Canned Meat, Poultry, or Asian Food) to facilitate efficient browsing.

Geographic Map: Geographic data is stored using latitude and longitude coordinate systems to perform location searches.

Characteristics of an Algorithm:
Input: Accepts zero or more clearly defined inputs.
Output: Produces at least one output.
Unambiguity: Every step must be clear, simple, and unambiguous.
Finiteness: Must terminate after a finite number of steps.
Effectiveness: Every step must be basic enough to be carried out effectively and have a distinct purpose.
Algorithmic Flow Model:
Real-World Algorithm Example (Cooking Pancit Canton):
Boil water.
Put noodles in boiling water.
Prepare the sauce on a plate.
Drain the water.
Put noodles in the sauce.
Stir until noodles are thoroughly covered with the sauce.
Serve the pancit canton.
Computational Algorithm Pseudocode (Addition of Two Numbers):
DECLARE num1, num2 and sum;
INPUT num1 and num2;
READ num1 and num2;
PROCESS sum = num1 + num2;
OUTPUT sum;
```
- Java Implementation (Addition of Two Numbers):
java import java.util.Scanner;
public class AddTwoNumbers { public static void main(String[] args) { int num1, num2, sum; Scanner in = new Scanner(System.in); System.out.println("Enter First Integer"); num1 = in.nextInt(); System.out.println("Enter Second Integer"); num2 = in.nextInt(); sum = num1 + num2; System.out.println("The sum of two input integer is " + sum); } } ```
Algorithm Complexity Analysis:
Time Complexity: Measures the execution time required by an algorithm to complete as a function of the input size.
Space Complexity: Measures the total memory space required by an algorithm during execution.
Space Complexity Components:
Instruction Space: Memory allocated to store the executable binary code, which scales with code size.
Data Space: Memory allocated to store variables, constants, arrays, and dynamic data structure nodes.
Environment Space: Memory allocated to store execution context state (such as stack frames, local variables, and return addresses) required to resume suspended functions.
Abstraction and Data Types
Concept of Abstraction:
Abstraction is the programming practice of suppressing complex internal implementation details while exposing only essential interfaces and functionality to the user.
It shifts developer focus toward what an object does rather than how it performs its internal operations.
Real-World Example of Abstraction:
An Automated Teller Machine (ATM) Center (e.g., PSBank, BPI, BDO, Metrobank) allows users to perform banking transactions through simple screen buttons without exposing vault hardware or network protocols.

Programming Example of Abstraction:
Invoking
System.out.println("Hello");outputs text to the console without requiring the developer to implement low-level stream buffers or operating-system display drivers.
Key Benefits of Abstraction:
Simplifies program design.
Enhances code readability and maintainability.
Reduces overall structural complexity.
Promotes modular and reusable software architectures.
Everyday Life Examples of Abstraction:
Driving a car (using steering wheel and pedals without operating engine mechanics).
Using a smartphone touchscreen.
Flipping a light switch.
Categories of Data Types:
Primitive Data Types: Basic, language-provided data types that hold single primitive values directly.
int: Stores integers (e.g.,25).double: Stores double-precision floating-point numbers (e.g.,3.14).char: Stores single characters (e.g.,'A').Boolean: Stores logical values (TrueorFalse).string: Stores textual sequences (e.g.,"Hello").Abstract Data Types (ADTs) / User-Defined Data Types: High-level structures built by aggregating primitive data types to represent complex real-world entities. They specify available operations while isolating structural implementation details.
Examples:
Student,Employee,Book.
ADT Java Class Example:
class Student {
String name;
int age;
}
```
- Instances defined from ADTs (e.g., `Student s1; Student s2;`) manage structured fields (`studentName`, `studentAge`, `studentCourse`).
# Methods, Parameters, and Parameter Passing in Java
- **Parameter vs. Argument Definitions:**
- **Parameter:** A variable declaration in a method definition (e.g., `String name` in `void greet(String name)`).
- **Argument:** The actual value passed into a method when it is called (e.g., `"John"` in `greet("John")`).
- Multi-Parameter Method Signature Example:
java public class Main { static void myMethod(String name, int age) { System.out.println(name + " is " + age); }
public static void main(String[] args) {
myMethod("Jepoy", 24);
myMethod("Mikoy", 5);
myMethod("Jef", 25);
}
} ```
When invoking multi-parameter methods, the call must provide the exact count of arguments matching the parameter types in their declared sequential order.
Java Parameter Passing Mechanism (Pass-by-Value):
Java strictly utilizes Pass-by-Value for parameter passing. When a primitive variable is passed into a method, a copy of the argument's value is created in memory.
Changes made to the parameter inside the called method scope do not affect the original variable in the caller scope.
Demonstration of Pass-by-Value (Value Preservation Example):
public class Square_abs {
static void square(int x) {
x = x * x;
}
public static void main(String[] args) {
int a = 5;
square(a);
System.out.println(a);
}
}
```
- **Execution Analysis:** The variable `a` is initialized to `5`. Calling `square(a)` passes a copy of value `5` into local parameter `x`. The local expression `x = x * x` modifies `x` to `25`, but `a` remains `5`. The output printed to the console is `5`.
# Array Data Structure and Operations
- **Definition and Properties:**
- An Array is a linear collection of fixed size that holds homogeneous data items stored in contiguous memory locations.
- Access to elements is performed using an integer index.
- **Array Index vs. Memory Address:** An array index is a relative key value ranging from to . A memory address represents the exact physical RAM location allocated to store a value.

- Array Instantiation Syntaxes in Java:
- Declaration without allocation: `String[] cars;`
- Inline literal initialization: `String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};`
- Explicit size allocation: `String[] cars = new String[4];`
- **Basic Array Operations:**
- **1. Traversal:** Iterating through an array to read every element sequentially.
```java_traversal
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
```
- **2. Insertion:** Adding an item at a targeted index. Requires shifting existing elements from that position to the right to prevent data overwrites.
```java_insertion
String[] cars = new String[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
int position = 2;
// Shift elements to the right
for (int i = 3; i >= position; i--) {
cars[i + 1] = cars[i];
}
cars[position] = "Toyota";
for (String car : cars) {
System.out.println(car);
}
```
- **3. Deletion:** Removing an item at a specified index. Requires shifting subsequent elements left and resetting the trailing slot to `null`.
```java_deletion
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int position = 1;
// Shift elements left
for (int i = position; i < cars.length - 1; i++) {
cars[i] = cars[i + 1];
}
cars[cars.length - 1] = null;
for (String car : cars) {
System.out.println(car);
}
```
- **4. Searching:**
- *Search by Index:* Direct lookup returning `cars[2]` in time complexity.
- *Search by Value (Linear Search):* Sequentially evaluating entries in time complexity.
```java_search
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
String target = "Ford";
boolean found = false;
for (int i = 0; i < cars.length; i++) {
if (cars[i].equals(target)) {
System.out.println(target + " found at index " + i);
found = true;
break;
}
}
if (!found) System.out.println("Not Found");
```
- **5. Update:** Modifying a target value at a known index directly (`cars[2] = "Honda";`).
- **6. Display:** Printing array contents completely.
- **Big O Performance Summary for Arrays:**
- Direct index lookup and direct updates take constant time because memory addresses are calculated using the base address and index offset.
- Operations that shift or check items sequentially (traversal, insertion in middle, deletion, search by value) run in linear time , scaling directly with array size .
- Classroom Array Activity Walkthrough:
- Given: `String[] fruits = {"Apple", "Banana", "Orange", "Mango"};`
- Step 1: Traverse and display all fruits.
- Step 2: Insert `"Grapes"` at index `2` (shifts `"Orange"` and `"Mango"` right).
- Step 3: Delete `"Banana"` (shifts subsequent elements left).
- Step 4: Search for `"Mango"` by value.
- Step 5: Update `"Orange"` to `"Pineapple"`.
- Step 6: Display the final array content.
# Linear vs. Non-Linear Data Structures
- **Linear Data Structures:**
- Data elements are arranged sequentially in a contiguous or linked linear progression.
- Each element is attached directly to its previous and next adjacent elements.
- Categories of Linear Data Structures:
- **Static Data Structures:** Memory size is fixed at declaration time (e.g., standard Arrays). Simple to access, but can waste unused allocated space.
- **Dynamic Data Structures:** Memory grows or shrinks dynamically at runtime, optimizing space complexity (e.g., Stacks, Queues, LinkedLists).
- **Non-Linear Data Structures:**
- Elements are organized non-sequentially and can branch out across hierarchical or networked pathways.
- Examples: Trees, Graphs.

# The LinkedList Data Structure
- **Overview:**
- A LinkedList stores elements (called **nodes**) that are not required to occupy contiguous physical memory slots. Nodes are scattered in memory and connected dynamically using reference pointers.
- Java's built-in `LinkedList` class in `java.util` provides a **Doubly LinkedList** implementation.
- **Node Anatomy in a Doubly LinkedList:**
- **`Prev`:** Pointer storing the memory address of the previous node (set to `null` at the head node).
- **`Data`:** Stores the actual data element.
- **`Next`:** Pointer storing the memory address of the next node (set to `null` at the tail node).

- Low-Level Custom Node Definition in Java:
java public class LinkedListSample { Node head;
static class Node {
int value;
Node next;
Node(int d) {
value = d;
next = null;
}
}
public static void main(String[] args) {
LinkedListSample linkedList = new LinkedListSample();
linkedList.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
// Connect nodes
linkedList.head.next = second;
second.next = third;
// Traverse and print
Node current = linkedList.head;
while (current != null) {
System.out.print(current.value + " ");
current = current.next;
}
}
} ```
Structural Comparison:
LinkedListvs.ArrayList:
Characteristic | LinkedList | ArrayList |
|---|---|---|
Interfaces Implemented | Implements | Implements |
Node Storage Layout | Stores 3 fields ( | Stores a single value slot per element. |
Underlying System | Doubly-Linked List architecture. | Resizable Array architecture. |
Insertion / Deletion | Efficient re-linking of | Requires shifting all elements after insertion/deletion point. |
Accessing Elements | Requires sequential traversal from the head node (). | Direct index access (). |
LinkedList Operations (Deque & Queue Implementations):
addFirst(E e): Inserts element at the start of the list.addLast(E e): Appends element at the end of the list.getFirst(): Returns the first element without removal.getLast(): Returns the last element without removal.removeFirst(): Removes and returns the first element.removeLast(): Removes and returns the last element.peek(): Retrieves the head element of the queue, returningnullif empty.poll(): Retrieves and removes the head element of the queue, returningnullif empty.offer(E e): Adds an element as the tail of the queue.
Stack Data Structure
Definition & Operational Logic:
A Stack is a linear data structure operating under Last-In, First-Out (LIFO) or First-In, Last-Out (FILO) principles.
Elements are inserted and removed from a single point called the top.
Real-World Stack Examples:
A stack of folded clothes or a stack of dinner plates.
Web browser navigation history (navigating back pops the most recently visited URL).

Core Stack Interface Operations:
push(x): Inserts itemxonto the top of the stack.pop(): Removes and returns the item currently on top of the stack.isEmpty(): Evaluates if the stack contains zero elements (returnstruewhentop == -1ortop == null).isFull(): Evaluates if an array-based stack has reached maximum capacity.peek(): Inspects and returns the item at the top without removing it.size(): Returns total item count currently residing in the stack.
Stack Operational Errors:
STACK OVERFLOW: Occurs when executing
push()on a stack that has reached capacity (top == LIMIT - 1).STACK UNDERFLOW: Occurs when executing
pop()on an empty stack (top == -1ortop == null).
Operational Step-by-Step Execution Trace Example:
Starting with an empty stack (
top = -1) bounded by size5:
pop()TriggersSTACK UNDERFLOWerror.push('x')Stack stores['x'],top = 0.pop()Removes'x', stack becomes empty,top = -1.push('y'),push('a'),push('k'),push('i'),push('M')Stack becomes['y', 'a', 'k', 'i', 'M'],top = 4.isFull()ReturnsTRUEbecausetop == 4(capacity limit5).peek()Returns'M'without modifyingtop.Sequential
pop()calls empty the stack item by item down totop = -1, whereisEmpty()evaluates toTRUE.
Stack Implementations (Array vs. LinkedList)
1. Fixed-Array Stack Implementation in Java:
public class ArrayStack {
static final int LIMIT = 5;
static char[] stck = new char[LIMIT];
static int top = -1;
static boolean isEmpty() {
return top == -1;
}
static boolean isFull() {
return top == LIMIT - 1;
}
static void push(char data) {
if (isFull()) {
System.out.println("STACK OVERFLOW!");
} else {
top++;
stck[top] = data;
System.out.println("Pushed " + data);
}
}
static void pop() {
if (isEmpty()) {
System.out.println("STACK UNDERFLOW!");
} else {
System.out.println("Popped " + stck[top]);
stck[top] = '\0';
top--;
}
}
static char peek() {
if (isEmpty()) {
System.out.println("Stack is Empty");
return '\0';
}
return stck[top];
}
static int cnt() {
return top + 1;
}
static void display() {
if (isEmpty()) {
System.out.println("Stack is Empty!");
} else {
for (int i = top; i >= 0; i--) {
System.out.println(stck[i]);
}
}
}
}
```
- **2. Dynamic LinkedList Stack Implementation in Java:**
java public class LinkedListStack { static class Node { char data; Node next;
Node(char data) {
this.data = data;
this.next = null;
}
}
static Node top = null;
static boolean isEmpty() {
return top == null;
}
static void push(char data) {
Node newNode = new Node(data);
newNode.next = top;
top = newNode;
System.out.println("Pushed " + data);
}
static void pop() {
if (isEmpty()) {
System.out.println("STACK UNDERFLOW!");
} else {
System.out.println("Popped " + top.data);
top = top.next;
}
}
static char peek() {
if (isEmpty()) {
System.out.println("Stack is Empty");
return '\0';
}
return top.data;
}
static int cnt() {
int count = 0;
Node current = top;
while (current != null) {
count++;
current = current.next;
}
return count;
}
static void display() {
if (isEmpty()) {
System.out.println("Stack is Empty!");
} else {
Node current = top;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
}
} ```
Searching Algorithms in Java
Definition of Search: The algorithmic procedure of identifying, locating, and retrieving a specific target element from within a data structure.
Categories of Search Algorithms:
Sequential Search: Scans elements iteratively from start to end. Works on unsorted data collections (e.g., Linear Search).
Interval Search: Operates by repeatedly bisecting sorted data collections to eliminate search spaces efficiently (e.g., Binary Search).
Linear Search Algorithm:
Evaluates each contiguous slot in an array sequentially until a match is found or the array ends.
Worst-Case Time Complexity: .
Linear Search Formal Step-by-Step Algorithm:
Step 1: Set to
Step 2: If , then go to Step 7
Step 3: If , then go to Step 6
Step 4: Set to
Step 5: Go to Step 2
Step 6: Print "Element Found at index " and go to Step 8
Step 7: Print "Element not found"
Step 8: Exit
Linear Search Complete Java Implementation:
public class LinearSearch {
public static int search(int arr[], int x) {
int n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int arr[] = {2, 3, 4, 10, 40};
int x = 10;
int result = search(arr, x);
if (result == -1) {
System.out.print("Element is not present in array");
} else {
System.out.print("Element is present at index " + result);
}
}
}
```
- **Binary Search Algorithm:**
- Uses a **divide and conquer** strategy that requires the data set to be sorted in advance.
- Divides search bounds in half during each iteration, discarding half of the search interval depending on whether the target value is higher or lower than the midpoint.
- Midpoint formula calculation:
- Binary Search Formal Step-by-Step Algorithm:
- Step 1: Set
- Step 2: Set
- Step 3: If , go to Step 12
- Step 4: Set
- Step 5: If
- Step 6: Set
- Step 7: If
- Step 8: Set
- Step 9: If , go to Step 11
- Step 10: Go to Step 3
- Step 11: Print "Element Found at index " and go to Step 13
- Step 12: Print "Element not found"
- Step 13: Exit
- Binary Search Complete Java Implementation (Recursive):
java public class BinarySearch { int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2;
if (arr[mid] == x) {
return mid;
}
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
public static void main(String[] args) {
BinarySearch ob = new BinarySearch();
int arr[] = {2, 3, 4, 10, 40};
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1) {
System.out.println("Element not present");
} else {
System.out.println("Element found at index " + result);
}
}
} ```