Data Structures & Algorithms Basics
Data Structures and Algorithms - Study Notes
Big O Notation
Big O notation is a mathematical notation used to describe the performance or scalability of an algorithm. It expresses how the runtime (or space) of an algorithm grows as the size of the input increases. The goal is not to measure exact execution time (which varies by machine), but to understand the growth rate ā how much slower an algorithm becomes when the input becomes very large.
Why Big O Matters
Helps determine if an algorithm will scale well with large data sets.
Certain operations become more or less costly depending on the data structure used. For example, accessing an array element by index is fast (O(1)), but arrays have fixed size; resizing them is costly (O(n)).
Technical interviews at major companies (Google, Microsoft, Amazon) often require Big O analysis.
Knowing Big O makes you a better developer by enabling you to choose efficient algorithms and data structures.
Common Runtime Complexities
O(1) ā Constant Time
The algorithm takes the same amount of time regardless of input size. Example: accessing the first element of an array.
public void printFirst(int[] numbers) {
System.out.println(numbers[0]); // single operation, O(1)
}Even if there are multiple constant-time operations, the runtime remains O(1) because the total time does not depend on n.
O(n) ā Linear Time
Runtime grows linearly and directly with the size of the input. Example: iterating over all items in an array.
public void printAll(int[] numbers) {
for (int number : numbers) {
System.out.println(number); // O(n)
}
}Dropping constants: If there are two loops (e.g., O(2n)), we simplify to O(n) because constants do not affect growth rate. Similarly, O(n+1) becomes O(n).
O(n2) ā Quadratic Time
Occurs with nested loops where each iteration runs another full loop. Example: printing all pairs in an array.
public void printCombinations(int[] numbers) {
for (int first : numbers) { // O(n)
for (int second : numbers) { // O(n)
System.out.println(first + ", " + second);
}
}
}If an additional linear operation (O(n)) is present alongside O(n2), we drop the smaller term (n) because n2 dominates for large n. Thus overall complexity is O(n2).
A triple nested loop yields O(n3).
O(logn) ā Logarithmic Time
Runtime grows slowly as input size increases. The algorithm reduces the problem size by half in each step (e.g., binary search on a sorted array). For 1 million items, a logarithmic algorithm may need only ~20 comparisons.
Comparison of growth curves:
Linear (O(n)) grows at constant rate.
Logarithmic (O(logn)) slows down, making it much more efficient for large inputs.
O(2n) ā Exponential Time
The opposite of logarithmic: runtime doubles with each additional input. Such algorithms become extremely slow quickly and are not scalable (e.g., naive recursive Fibonacci).
Space Complexity
Big O also describes how much extra memory an algorithm requires relative to input size.
O(1) space: Only a fixed amount of extra memory (e.g., a loop variable).
O(n) space: Allocating an array of size n as a copy.
We only count additional space beyond the input itself.
Key Rule: In Big O analysis, always consider the worst-case scenario. For example, linear search is O(1) in the best case (first element), but O(n) in the worst case (last element). The worst case dominates.
Arrays
Arrays are the simplest data structure for storing a list of items sequentially in memory. They are built into most programming languages.
How Arrays Work
Items are stored in contiguous memory locations.
Because of this sequential layout, looking up an item by its index is O(1) ā the memory address is calculated directly via a formula (base address + index Ć element size).
In Java and many languages, arrays have a fixed size specified at creation.
Strengths and Weaknesses
Operation | Complexity | Explanation |
|---|---|---|
Lookup by index | O(1) | Direct memory address calculation. |
Insertion at end (if space available) | O(1) | No shifting needed. |
Insertion at end (if array full) | O(n) | Must resize: allocate new array (usually double the size) and copy all existing items. |
Insertion at beginning or middle | O(n) | Requires shifting all subsequent elements to the right. |
Deletion from end | O(1) | Simply remove the last item. |
Deletion from beginning or middle | O(n) | Must shift all subsequent elements left to fill the gap. |
Search for a value | O(n) | Linear scan (worst case). |
Arrays in Java
Declaring an array:
int[] numbers = new int[3];Initializing with values:
int[] numbers = {10, 20, 30};Accessing:
numbers[0]Length:
numbers.length(fixed)To print contents: use
java.util.Arrays.toString(numbers).
Static nature: Once created, size cannot change. To add more items, you must create a new larger array and copy elements.
Dynamic Array Implementations in Java
Java provides two built-in dynamic arrays in java.util:
Vector: Grows by 100% of its size when full; all methods are synchronized (thread-safe).ArrayList: Grows by 50% of its size; methods are not synchronized (better performance for single-threaded use). More commonly used.
Building a Dynamic Array from Scratch (Exercise)
A custom Array class that automatically grows and shrinks:
Fields:
private int[] items(underlying fixed array)private int count(number of actual items stored)
Constructor: Takes initial capacity, allocates
itemsof that size, setscount = 0.insert(int item)method:If array is full (
count == items.length), resize: create new array of sizecount * 2, copy existing items, then setitems = newItems.Place the new item at index
countand incrementcount.
removeAt(int index)method:Validate index (throw
IllegalArgumentExceptionif out of range).Shift items left:
for (int i = index; i < count - 1; i++) items[i] = items[i+1];Decrement
count.
indexOf(int item)method:Linear scan from
0tocount-1, return index if found; else return-1.Complexity: O(n) worst case.
print()method: Loop from0tocountand print each item.
Edge cases to handle: Empty array, index out of bounds, resizing when full.
Linked Lists
Linked lists solve many limitations of arrays: they can grow and shrink automatically without the cost of resizing. They consist of a sequence of nodes, where each node contains a value and a reference (pointer) to the next node.
Structure
Head: The first node in the list.
Tail: The last node (its
nextpointer isnull).Nodes are not necessarily stored contiguously in memory; each node must explicitly store the address of the next node.
Time Complexities
Operation | Complexity | Explanation |
|---|---|---|
Search for a value | O(n) | Must traverse from head to tail. |
Lookup by index | O(n) | Same as search; no direct index access. |
Insert at beginning | O(1) | Create new node, point its |
Insert at end | O(1) | Create new node, point tail's |
Insert in the middle (after a known node) | O(1) to update links, but finding the node is O(n). | Overall O(n). |
Delete from beginning | O(1) | Point head to the second node. Also set the old head's |
Delete from end | O(n) | Must traverse to find the second-to-last node (previous node of tail). Update tail and break link. |
Delete from middle | O(n) | Traverse to find the node and its predecessor, then relink. |
Java's LinkedList
java.util.LinkedList<E>provides a doubly linked list (each node has references to both next and previous).Common methods:
addLast(E e)ā adds at endaddFirst(E e)ā adds at beginningremoveLast()/removeFirst()remove(int index)contains(Object o)ā O(n) searchindexOf(Object o)ā O(n) searchsize()toArray()ā converts to array
Building a Linked List from Scratch (Exercise)
Create a custom LinkedList class with an inner Node class.
Node Class (private inner class)
private class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
}LinkedList Class
Fields: private Node first; (head), private Node last; (tail).
addLast(int item)
Create a new
Nodewith the given value.If list is empty (
first == null), set bothfirstandlastto the new node.Else: set
last.next = newNode, then setlast = newNode.
addFirst(int item)
Create a new
Node.If empty, set both
firstandlastto it.Else: set
newNode.next = first, then setfirst = newNode.
indexOf(int item)
Traverse from
firstwith acurrentpointer and anindexcounter.For each node, if
current.value == item, returnindex.If reaches end, return
-1. Complexity: O(n).
contains(int item)
Simply return
indexOf(item) != -1.
removeFirst()
If list is empty, throw
NoSuchElementException.If only one node (
first == last), set bothfirstandlasttonull.Else:
Store
second = first.next.Remove link:
first.next = null.Update
first = second.
removeLast()
If empty, throw exception.
If single node, set
first = last = null.Else:
Find the previous node of the last node. Use a helper method
getPrevious(Node node)that traverses the list untilcurrent.next == node.Set
last = previous.Remove link:
last.next = null.
Helper method getPrevious(Node node) returns the node before the given node, or null if no such node.
Edge cases: Empty list, single element list. Always check and throw appropriate exceptions (
NoSuchElementExceptionfor illegal operation on empty list).
Summary of Key Differences: Arrays vs Linked Lists
Memory layout: Arrays are contiguous; linked lists are scattered (nodes linked by pointers).
Size flexibility: Arrays have fixed size (dynamic arrays by copying); linked lists grow/shrink naturally.
Index lookup: Arrays O(1); linked lists O(n).
Insertion/deletion at ends: Linked lists O(1) (if tail maintained); arrays O(n) due to shifting or resizing.
Insertion/deletion in middle: Both O(n) (linked list requires traversal to find position).
Memory overhead: Linked lists need extra memory for the
nextpointer per element.

Ask anything
We've read this whole study set, so questions about it get the best answers.