Java Data Structures and Algorithms
Data Structures and Algorithms in Java
1. Data Structures and Why They Matter
Data is information stored or processed by a computer. A data structure is a way of organizing that information so that particular operations can be performed effectively.
The choice of data structure affects:
Time complexity: how the time required for an operation changes as the input grows.
Space complexity: how much memory an operation or algorithm requires.
Operation costs: how efficiently data can be accessed, searched, inserted, deleted, or rearranged.
Application suitability: different structures are useful for different patterns of data and operations.
For example, arrays place elements in indexed positions and support fast access by index, but they have a fixed length. Linked lists can grow as nodes are added and can use memory locations that are not adjacent, but accessing an element generally requires moving through earlier nodes.
A data structure is not simply a container: it determines how data is arranged and therefore influences the efficiency of the algorithms that operate on it.
2. Linear and Nonlinear Data Structures
Linear structures
A linear data structure arranges elements in a sequence. Except at the ends, each element has a preceding and following element in that sequence.
Examples include:
Arrays: elements are accessed through indexes.
Linked lists: nodes connect to one another using references.
Stacks: elements are added and removed at one end.
Queues: elements are added at one end and removed at the other.
Linear structures often have identifiable ends or boundaries, such as the first and last array indexes, the head and tail of a list, or the front and rear of a queue.
Nonlinear structures
A nonlinear data structure organizes elements in relationships that are not a single sequence. One element may connect to multiple others, and the structure may have branches or networks.
Examples include:
Trees: organize nodes hierarchically.
Graphs: represent general relationships among vertices.
A binary tree limits each node to at most two children; other trees can allow more.
3. Arrays
An array is a linear structure containing a fixed number of elements of one declared type. In Java, an array’s length is determined when it is created and cannot later be changed.
Indexing and memory access
Array indexes start at zero. If an array contains n elements, its valid indexes run from 0 to n−1.
Arrays support direct access: the position of an element can be calculated from its index, so accessing a known index takes constant time, O(1). Conceptually, for elements of width w and a base address b, the address of element i is:
This is why array indexing does not require scanning earlier elements.
In a two-dimensional array, two indexes identify an element: one for its row and one for its column. A nested loop is commonly used to visit every element. Java two-dimensional arrays are arrays of arrays; they can be treated like a matrix when each row has the same length.
Creating and initializing arrays in Java
A one-dimensional integer array can be created with a specified length:
int[] values = new int[6];It can also be created with its initial values:
int[] values = {3, 6, 2, 9, 5, 1};The length is available through the array’s length field. A loop that visits every array element should use indexes from zero up to, but not including, values.length.
A two-dimensional array can be created with a specified number of rows and columns:
int[][] grid = new int[3][4];Nested loops can visit its elements, using one index for the row and one for the column.
Common array operations and costs
Access by index: O(1).
Visit every element: O(n).
Linear search: O(n) in the worst case.
Insert or delete within the array: often O(n), because elements may need to be shifted.
Resize: a Java array cannot be resized; a larger array must be created and values copied.
Strengths and limitations
Arrays are useful when the number of elements is known or stable, and when frequent indexed access is important. They can represent sequential data compactly and make iteration straightforward.
Their main limitations are:
Fixed length: an array cannot grow beyond its declared capacity.
Unused capacity: if an array is larger than the number of elements stored, some allocated space is unused.
Contiguous-space requirement in the conceptual model: an array is treated as a continuous block of element positions, unlike a linked list whose nodes can be distributed in memory.
Costly insertion and deletion: adding or removing an element in the middle typically requires shifting later elements.
Arrays can also replace many individually named variables. Instead of creating a separate variable for each student’s score, a program can store the scores in one array and access each score by index.
4. Stacks
A stack is a linear data structure that follows last in, first out (LIFO). The most recently added element is the first one removed. A stack of plates is a familiar example: the top plate must be removed before the plates below it can be reached.
The top of the stack is the only end used for insertion and removal.
Core operations
Push: add an element to the top.
Pop: remove and return the top element.
Peek: return the top element without removing it.
Check emptiness: determine whether the stack contains elements.
Size: report the number of elements.
With a suitable array, linked-list, or Java collection implementation, these operations are typically O(1). An array-based stack can be fixed in capacity unless it resizes.
Stack implementations in Java
Java provides a Stack class, but for many new programs a Deque implementation such as ArrayDeque is generally preferred for stack operations.
Deque<Integer> stack = new ArrayDeque<>();
stack.push(4);
stack.push(9);
int top = stack.peek(); // 9
int removed = stack.pop(); // 9A stack implementation must account for operations on an empty stack; attempting to remove a nonexistent element cannot produce a valid stack value.
Applications
Stacks are used in:
Recursion: each unfinished method call is represented by an activation record on the call stack.
Expression processing: stacks help parse expressions and manage operators or nested structures.
Browser history: visiting pages adds navigation states; going back removes the most recent state.
Undo and redo: recent actions can be stored and reversed in last-in-first-out order.
Strengths and limitations
Stacks provide fast access to the most recently added element and support a restricted set of operations efficiently. That restriction is also a limitation: an element in the middle cannot be accessed or removed directly without first handling elements above it.
5. Queues
A queue is a linear data structure that follows first in, first out (FIFO). The first element added is the first one removed. A line of people waiting for service illustrates this rule.
A queue has two ends:
The rear is where new elements are inserted.
The front is where elements are removed.
Core operations
Enqueue: insert an element at the rear.
Dequeue: remove an element from the front.
Peek at the front: inspect the next element to be removed.
Peek at the rear: inspect the most recently added element, if the implementation supports it.
Check emptiness and size: determine whether the queue has elements and how many it contains.
In a well-designed queue implementation, insertion and removal are typically O(1). A simple array implementation that shifts all remaining elements after each removal can make removal O(n); circular arrays, linked lists, or library implementations avoid that repeated shifting.
Queues in Java
Java provides the Queue interface. A common implementation for a basic queue is ArrayDeque.
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(5);
queue.offer(8);
int next = queue.poll(); // 5The interface separates the queue operations from the implementation used to provide them.
Applications
Queues are useful whenever items must be handled in arrival order. Applications include:
Operating-system scheduling: processes or tasks may wait in queues. Scheduling methods can include FIFO and round-robin approaches.
Playlists: the next queued item can play after the current one.
Interrupt and task handling: work can wait until the system is ready to process it.
Other waiting-line systems: tasks can be processed in the order they arrive.
Queues are efficient for ordered processing, but their FIFO rule restricts where elements can be inserted and removed.
6. Linked Lists
A linked list is a linear structure made of nodes. Each node stores data and one or more references that connect it to other nodes. The nodes do not need to occupy consecutive memory locations.
A singly linked node typically contains:
A data field.
A reference to the next node.
The first node is reached through a reference called the head. The last node in a standard singly linked list has a null next reference. Some implementations also maintain a tail reference to the final node.
Access and memory behavior
A linked list can grow or shrink as nodes are added or removed, so it does not require a fixed capacity in the way an ordinary Java array does. It can therefore use memory in separate available locations.
Unlike an array, a linked list does not generally support direct indexed access. To reach a particular position, traversal starts at the head and follows links one node at a time. Searching for an element is typically O(n).
Inserting or deleting a node can be efficient when the relevant position or neighboring node is already known: references can be changed instead of shifting a block of elements. Finding that position may still require O(n) traversal.
The head reference must be preserved. Losing it can make the nodes in the list unreachable from the program’s starting reference.
Types of linked lists
Singly linked list
Each node points to the next node. Traversal proceeds forward only.
Doubly linked list
Each node has references to both the next and previous nodes. This allows forward and backward traversal, at the cost of storing and maintaining an extra reference per node.
Circular linked list
The last node points back to the first instead of pointing to null. In a circular doubly linked list, the list can also be traversed backward through previous references.
Using linked lists in Java
Java’s collection framework provides a LinkedList class. It supports operations such as adding and removing elements at the beginning or end, inserting at an index, finding the size, and checking whether an element is present.
An iterator can traverse a collection element by element. This is especially useful when an implementation should not rely on repeatedly accessing elements by index.
Strengths and limitations
Linked lists are useful when a structure must grow dynamically or when insertion and deletion are frequent and positions are already known. They avoid shifting all later elements for a local insertion or deletion.
Their limitations include:
No direct random access: reaching an element requires traversal.
Traversal cost: finding an element or position is generally O(n).
Reference overhead: each node stores links in addition to its data.
Dependence on the head: the list becomes inaccessible if its starting reference is lost.
7. Trees and Binary Trees
A tree is a nonlinear data structure that organizes nodes hierarchically. Edges connect parent nodes to child nodes.
Tree terminology
Root: the topmost node, with no parent.
Parent and child: a node directly above another is its parent; the lower node is its child.
Siblings: nodes with the same parent.
Leaf: a node with no children.
Subtree: a node and the descendants connected below it.
Trees model structures such as folders and files, where items are arranged in levels.
Binary trees
A binary tree is a tree in which each node has at most two children: a left child and a right child. A node may have zero, one, or two children.
A general binary tree does not necessarily impose rules on the values stored in its nodes. Different kinds of binary trees add further rules.
Binary search trees
A binary search tree (BST) orders values so that, for each node:
Values in its left subtree are less than the node’s value.
Values in its right subtree are greater than the node’s value.
An implementation must define how it handles duplicate values; for example, it may reject duplicates or consistently place them on one side.
Searching, inserting, and deleting can take O(logn) time in a reasonably balanced BST. In a badly skewed tree, these operations can take O(n) time. The tree’s shape therefore matters to its performance.
Why trees are useful
Trees support hierarchical organization and can guide efficient searching. In a BST, comparisons can eliminate a subtree from consideration: if the target is smaller than the current value, search proceeds left; if greater, it proceeds right.
Trees also have variants with additional structural rules. The source names balanced tree families, including AVL and red-black trees, as variations intended to control tree shape.
8. Tree Traversals
A traversal visits the nodes of a tree in a defined order. For a binary tree, three standard depth-first traversal orders are preorder, inorder, and postorder.
Suppose a node has a left subtree, a right subtree, and its own value:
Preorder: root, left, right
Visit the root.
Traverse the left subtree.
Traverse the right subtree.
Preorder can be used to reproduce or copy a tree when the node values and structure are represented appropriately. It is also used to produce prefix notation from an expression tree.
Inorder: left, root, right
Traverse the left subtree.
Visit the root.
Traverse the right subtree.
For a BST, inorder traversal visits values in sorted order, provided that the BST ordering rules are followed.
Postorder: left, right, root
Traverse the left subtree.
Traverse the right subtree.
Visit the root.
Postorder is useful when children need to be handled before their parent, such as when deleting a tree. Applied to an expression tree, it produces postfix notation.
Recursive Java pattern
Tree traversals are naturally expressed recursively. Each call processes one node and then calls the traversal method on its children. A base case stops when the current node is null.
static void inorder(Node node) {
if (node == null) return;
inorder(node.left);
System.out.print(node.key + " ");
inorder(node.right);
}Preorder visits the node before the recursive calls; postorder visits it after them.
9. Algorithms and Complexity Analysis
An algorithm is a step-by-step method for solving a problem. A good algorithm should correctly address the problem, use resources appropriately, and be expressed clearly enough for its steps to be understood independently of a particular programming language.
Different algorithms can solve the same problem. Their efficiency can differ in time and memory use.
Time complexity
Time complexity describes how the number of operations grows with input size. It is commonly expressed using Big O notation, which describes an upper-bound growth rate while omitting constant factors and lower-order terms.
Examples include:
Constant time: O(1).
Linear time: O(n).
Logarithmic time: O(logn).
Quadratic time: O(n2).
The same algorithm can have different behavior in different cases:
Best case: the most favorable input.
Average case: typical expected behavior under stated assumptions.
Worst case: the greatest amount of work for an input of a given size.
Worst-case analysis is useful when a program must be prepared for the most demanding input.
Space complexity
Space complexity describes how memory use grows with input size. It includes auxiliary storage used by the algorithm, such as temporary arrays, nodes, or data structures.
An algorithm that scans an existing array without creating input-sized extra storage can use O(1) auxiliary space. An algorithm that creates a second array proportional to the input size uses O(n) auxiliary space.
Recursion also uses call-stack memory. Each unfinished recursive call needs space for its activation record, so recursion depth can affect space complexity.
Reasoning about common code patterns
A loop that processes each of n elements once usually takes O(n) time.
Two nested loops that each run about n times usually take O(n2) time.
A loop that repeatedly halves the remaining search range usually takes O(logn) time.
Sequential blocks add their costs; the term with the fastest growth dominates. For example, O(n2+n) simplifies to O(n2).
Nested loops multiply their iteration counts when each loop’s work is performed for each iteration of the outer loop.
Complexity describes growth as inputs get larger, not a precise number of seconds on a particular computer. A time–space trade-off arises when an algorithm uses extra memory to reduce the work required, or uses less memory at the cost of additional computation.
10. Searching Algorithms
Searching determines whether a target value is present and, if so, where it occurs.
Linear search
Linear search checks elements one at a time, beginning at the start of the collection. It stops when it finds the target or reaches the end.
If the target is at the beginning, only one comparison is needed. If it is at the end or is absent, the algorithm may inspect every element.
Best-case time: O(1).
Average-case and worst-case time: O(n).
Auxiliary space: O(1).
Linear search works on unsorted data and is simple to use. It is appropriate when collections are small or when the data is not ordered.
Binary search
Binary search repeatedly halves the remaining search interval. It requires a collection arranged in sorted order, or at least in an order that supports the comparisons used by the algorithm.
At each step:
Compare the target with the middle element.
If they match, return the middle index.
If the target is smaller, continue in the lower half.
If the target is larger, continue in the upper half.
If no elements remain, report that the target is absent.
For n elements, the worst-case time is O(logn). An iterative implementation uses O(1) auxiliary space; a recursive implementation uses call-stack space proportional to its recursion depth.
Binary search is much faster than linear search for sufficiently large sorted collections, but sorting the data first also has a cost. Whether binary search is useful depends on how often searching is performed and whether the data is already maintained in sorted order.
11. Greedy Algorithms and Dynamic Programming
Greedy algorithms
A greedy algorithm builds a solution step by step, selecting what appears to be the best available choice at each step. It aims for locally favorable choices while constructing a feasible solution.
Greedy methods are efficient when a problem has properties that make local choices lead to a globally optimal result. However, a locally optimal choice does not guarantee a globally optimal solution for every problem.
Example: choosing a route
Suppose two routes lead from Bangalore to Delhi:
Bangalore to Mumbai takes 2 hours, followed by 7 hours from Mumbai to Delhi: 9 hours total.
Bangalore to Hyderabad takes 3 hours, followed by 5 hours from Hyderabad to Delhi: 8 hours total.
A greedy choice based only on the next leg chooses Mumbai, because 2 hours is less than 3 hours. That choice leads to a 9-hour route, even though the route through Hyderabad takes 8 hours. This demonstrates why a local best choice may not be the overall best choice.
Problems associated with greedy methods
Greedy approaches are used in or associated with:
Fractional knapsack: choose quantities of items to maximize value under a weight limit.
Minimum spanning trees: Prim’s and Kruskal’s algorithms build low-weight spanning trees.
Dijkstra’s shortest-path algorithm: finds shortest paths from a source in graphs with nonnegative edge weights.
Some scheduling and selection problems.
A traveling-salesperson problem or a minimum vertex-cover problem may also be discussed in relation to greedy approaches, but a simple greedy choice is not guaranteed to solve every instance optimally.
Greedy versus dynamic programming
Dynamic programming solves a problem by breaking it into subproblems and storing results that can be reused. It considers how subproblem solutions contribute to larger solutions.
Greedy approach: makes a locally preferred choice at each step and typically does not revise that choice.
Dynamic programming: compares combinations of subproblem results to find an overall optimal solution when the problem has the necessary structure.
For the route example, dynamic programming can compare the total travel time of the complete alternatives and choose the 8-hour route. Greedy methods may use less memory and be faster, but their correctness depends on the specific problem’s properties. Dynamic programming often needs additional memory to store intermediate results.
12. Fractional Knapsack
The fractional knapsack problem selects items to maximize total profit while keeping total weight within a fixed capacity. Unlike the zero–one version, fractional knapsack allows part of an item to be selected.
For each item, define its value-to-weight ratio:
A greedy solution is:
Calculate the ratio for every item.
Sort items in descending order of ratio.
Add items in that order while capacity remains.
If the next item does not fit completely, take the fraction that fills the remaining capacity.
Add the corresponding fraction of its profit.
This greedy strategy is optimal for fractional knapsack because items can be divided. It is not generally an optimal method for the zero–one knapsack problem, in which an item must be either taken whole or not taken; dynamic programming is commonly used for that version.
For instance, if an item has weight w, profit p, and only a fraction f of it is taken, then the contribution to the knapsack is weight fw and profit fp.
13. Spanning Trees and Minimum Spanning Trees
A graph consists of vertices and edges. In a connected, undirected graph, a spanning tree connects every vertex without containing a cycle.
For a graph with V vertices, every spanning tree has exactly V−1 edges. A graph can have multiple different spanning trees.
A minimum spanning tree (MST) is a spanning tree with the smallest total edge weight among all spanning trees of a connected, weighted, undirected graph.
Prim’s algorithm
Prim’s algorithm grows one tree:
Start from any vertex.
Select the lowest-weight edge connecting a vertex already in the tree to a vertex outside it.
Add that edge and its new vertex.
Repeat until every vertex is included.
The algorithm must avoid adding an edge that would create a cycle within the growing tree.
Kruskal’s algorithm
Kruskal’s algorithm builds a forest of connected components:
Sort all edges by weight.
Consider them from lowest weight to highest.
Add an edge only if it connects two different components.
Stop when all vertices are connected.
A disjoint-set data structure is commonly used to check whether an edge would form a cycle.
Prim’s and Kruskal’s algorithms use different strategies but produce a minimum spanning tree when applied correctly to a connected, weighted, undirected graph.
14. Sorting Algorithms
Sorting arranges values into a chosen order, commonly ascending or descending. Sorting can make data easier to search, compare, or process.
Merge sort
Merge sort follows the divide-and-conquer approach:
Divide the input into smaller subarrays.
Continue dividing until each subarray contains one element.
Merge neighboring subarrays back together in sorted order.
Continue merging until one sorted array remains.
The merge step compares the first remaining elements of the two sorted subarrays and copies the smaller one into the output. When one subarray is exhausted, the remaining elements of the other subarray are copied directly.
Merge sort runs in O(nlogn) time in the best, average, and worst cases. A typical array-based implementation uses O(n) auxiliary space. It can be stable: equal-valued items retain their relative order if the merge step consistently chooses the earlier item when values are equal.
Quicksort
Quicksort also follows divide and conquer, but it partitions around a pivot:
Select a pivot value.
Rearrange the elements so that values smaller than the pivot are placed on one side and greater values on the other.
Place the pivot in its final sorted position.
Recursively sort the portions on either side of the pivot.
The pivot’s final position separates the two subproblems. Partitioning choices determine performance; repeatedly choosing a poor pivot can produce very uneven subproblems.
Average-case time: O(nlogn).
Worst-case time: O(n2).
Auxiliary space: typically O(logn) call-stack space on average, but it can reach O(n) with highly unbalanced recursion.
Stability: standard in-place quicksort is not stable.
Quicksort is often fast in practice, but its worst-case behavior is worse than merge sort’s. These algorithms illustrate the divide-and-conquer pattern: split a problem into smaller parts, solve those parts, and combine or use their results.
15. Recursion and Backtracking
Recursion
A recursive function calls itself to solve a smaller version of the same problem. A correct recursive method needs:
A base case that stops further calls.
A recursive case that moves the problem toward the base case.
Each call that has not finished remains on the call stack as an activation record. Once the deepest call returns, the earlier calls continue, in reverse order, until the original call completes.
Recursion is natural for problems whose structure repeats, including tree traversals and divide-and-conquer algorithms. It can make code concise, but it uses call-stack memory and can cause a stack overflow if it recurses too deeply or never reaches a base case. Java does not generally guarantee tail-call optimization, so recursive calls should not be assumed to use constant stack space.
Backtracking
Backtracking explores a sequence of choices, then reverses a choice when it cannot lead to a valid or desired solution. It is useful when a problem has multiple possible paths or combinations to explore.
A typical backtracking process is:
Choose one possible next step.
Record that choice and continue.
If the partial solution reaches a goal, record or return it.
If the path cannot succeed, undo the choice and try another.
Continue until all relevant choices have been explored.
A maze solver, for example, can try moving in allowed directions while marking visited positions. When a route reaches a dead end, the solver returns to the earlier position where another direction was available. If it must find multiple routes, it needs to restore path state during backtracking so that one explored path does not incorrectly block another.
Backtracking may examine many possibilities. Its worst-case running time can grow exponentially with the number of choices, so pruning invalid or unpromising paths is important.
16. Graphs and Graph Representations
A graph models relationships among objects. Its objects are called vertices (or nodes), and the connections between them are called edges.
Graphs can model friendships, routes among cities, and many other networks.
Common graph types
Directed graph: edges have a direction. An edge from one vertex to another does not automatically imply an edge back.
Undirected graph: edges have no direction; a connection works in both directions.
Connected graph: every vertex can be reached from every other vertex by following edges.
Disconnected graph: at least one pair of vertices cannot be connected by a path. A graph may contain an isolated vertex, with no incident edges.
Adjacency matrix
An adjacency matrix uses a two-dimensional structure to record which pairs of vertices have an edge. For an unweighted graph, the entry for a pair can be 1 if the edge exists and 0 if it does not.
For V vertices, an adjacency matrix uses O(V2) space. It makes checking whether a particular edge exists efficient, but visiting a vertex’s neighbors may require scanning an entire row.
For a weighted graph, an entry can store the edge’s weight. A separate convention is needed to represent no edge.
Adjacency list
An adjacency list stores a list of neighbors for each vertex. It is usually more space-efficient for sparse graphs because it stores the edges that exist rather than a full grid of possible edges.
With an adjacency list, a graph traversal typically takes O(V+E) time, where V is the number of vertices and E is the number of edges. With an adjacency matrix, traversal commonly takes O(V2) time.
17. Breadth-First Search (BFS)
Breadth-first search (BFS) visits a graph in layers, exploring nearby vertices before moving farther from the starting vertex. It uses a queue to preserve the order in which vertices are discovered.
BFS procedure
Choose a starting vertex.
Mark it as visited and enqueue it.
Dequeue the next vertex and examine its neighbors.
For each unvisited neighbor, mark it as visited and enqueue it.
Continue until the queue is empty.
Marking a vertex as visited when it is enqueued prevents it from being added repeatedly through different edges.
The order among vertices at the same distance depends on the order in which neighbors are stored and examined.
Complexity and uses
With an adjacency list, BFS takes O(V+E) time and uses O(V) additional space for the queue and visited information.
In an unweighted graph, BFS can find the shortest path in terms of number of edges from a source vertex to reachable vertices.
18. Depth-First Search (DFS)
Depth-first search (DFS) explores as far as possible along one path before returning to an earlier vertex and trying another path. It can be implemented with recursion or an explicit stack.
DFS procedure
Start at a vertex and mark it as visited.
Visit one unvisited neighbor.
Continue exploring unvisited neighbors as deeply as possible.
When a vertex has no unvisited neighbors, backtrack.
Stop when all reachable vertices have been visited.
As with BFS, the precise visit order depends on how neighbors are ordered. A visited set prevents repeated processing and infinite cycling through graph edges.
Complexity and uses
With an adjacency list, DFS takes O(V+E) time and uses O(V) additional space for the visited information and the recursion stack or explicit stack.
DFS is useful for exploring connectivity, traversing all vertices reachable from a start, and supporting other graph algorithms. Unlike BFS, DFS does not generally find the shortest path in an unweighted graph.
19. Hashing
Hashing is identified as a data-organization topic, but no detailed hashing concepts or operations are developed in the material.

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