Data Structures and Algorithms (DSA) are critical for optimizing how data is stored, accessed, and processed, directly affecting the performance of an application. This tutorial will guide you through the essential data structures and algorithms using the Java programming language.
Why Learn DSA in Java?
Java is a widely used, object-oriented, and platform-independent programming language that is particularly strong in building robust and scalable applications. Learning DSA in Java offers several benefits:
- Memory Management: Although Java manages memory through garbage collection, understanding how data structures work in Java gives you insights into memory handling, which can help you write efficient programs.
- Versatile: Java is known for its portability. Mastering DSA in Java makes it easier to transition to other object-oriented languages such as C++ or C#, as many modern languages share a similar syntax.
- Object-Oriented: Java supports object-oriented programming (OOP) principles, which means you can easily implement data structures as classes, making your code modular, reusable, and more maintainable.
- Strong Ecosystem: Java has a strong ecosystem for both web and mobile development, making it an excellent choice for building real-world applications using DSA concepts.
Prerequisite
Before diving into DSA with Java, you should be familiar with basic Java concepts. The following fundamental topics are prerequisites for learning DSA in Java:
- Setting Up Java Development Environment: You need a working Java Development Kit (JDK) and an Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA to write and run Java code.
- Variables & Data Types: In Java, variables store data values, and each variable has a specific type, such as
int
, float
, String
, etc. - Basic Input and Output: Java allows input from users via the console, using classes like
Scanner
, and output through System.out.print
and System.out.println
. - Operators: Java provides a variety of operators like arithmetic, relational, logical, etc., for performing operations on variables.
- Control Statements: Java supports decision-making statements like
if-else
and switch
, as well as loops like for
, while
, and do-while
. - Functions (Methods): Functions are blocks of code that perform specific tasks and can be called multiple times. Java supports both void and non-void methods.
- Object-Oriented Concepts: Java is an object-oriented language, meaning you should know about classes, objects, inheritance, polymorphism, and encapsulation.
- Collections Framework: Java provides a rich set of data structures, like
ArrayList
, HashMap
, LinkedList
, etc., but it’s recommended to implement your own data structures when learning DSA.
Click Here to Download and Install Java Development Kit (JDK) on Windows, Mac, and Linux
Learn DSA in Java
Mastering DSA in Java will enhance your problem-solving skills, making you well-prepared for coding interviews, competitive programming, and large-scale software development. Whether you're a beginner or an experienced developer, this guide will provide you with a solid foundation in Java-based data structures and algorithms.
1. Asymptotic Analysis of Algorithms
Asymptotic analysis helps evaluate the efficiency of an algorithm by examining how its execution time or memory usage grows relative to the input size.
- Big O Notation: It is used to describe the upper bound of an algorithm’s runtime in terms of its input size.
- Best, Average, and Worst Case: These terms refer to the performance of an algorithm in the best, average, and worst scenarios.
- Analysis of Loops and Recursion: Loops and recursive functions are key to understanding time complexity in algorithms.
Related Article
Analysis of Algorithms
2. Arrays
Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of memory management
Example:
Java
// Java Program to demonstrate Arrays
public class Geeks {
// Main Function
public static void main(String args[])
{
int[] arr = {10, 20, 30, 40};
System.out.println(arr[2]);
// Output: 30
}
}
3. ArrayList
Java ArrayList is a part of collections framework and it is a class of java.util package. It provides us with dynamic sized arrays in Java. The main advantage of ArrayList is, It automatically adjusts its capacity as elements are added or removed.
Java
// Java Program to demonstrate ArrayList
import java.util.ArrayList;
class Main {
public static void main (String[] args) {
// Creating an ArrayList
ArrayList<Integer> a = new ArrayList<Integer>();
// Adding Element in ArrayList
a.add(1);
a.add(2);
a.add(3);
// Printing ArrayList
System.out.println(a);
}
}
4. Strings
In Java, String is the type of objects that can store the sequence of characters enclosed by double quotes and every character is stored in 16 bits Strings in Java are immutable sequences of characters. Java provides a robust set of string operations, such as concatenation, substring extraction, and searching.
Example:
Java
// Java Program to demonstrate String
public class Geeks {
// Main Function
public static void main(String args[])
{
// creating Java string using new keyword
String str = "Hello";
System.out.println(str.length());
// Output: 5
System.out.println(str);
// Output: Hello
}
}
5. Stacks
A Stack in Java is a data structure that follows the Last In, First Out (LIFO) principle. In a stack, the last element added is the first one to be removed. In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek.
Example:
Java
// Java Program Implementing Stack Class
import java.util.Stack;
public class StackExample
{
public static void main(String[] args)
{
// Create a new stack
Stack<Integer> s = new Stack<>();
// Push elements onto the stack
s.push(1);
s.push(2);
s.push(3);
s.push(4);
// Pop elements from the stack
while(!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
6. Queues
In JAVA queues store and processes the data in FIFO(First In First Out) order. It is an ordered list of objects limited to inserting elements at the end of the list and deleting elements from the start of the list.
Example (Stack using Array):
Java
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
System.out.println(stack.pop()); // Output: 20
7. Linked List
A linked list is a dynamic data structure whose size increases as you add the elements and decreases as you remove the elements from the list and the elements (nodes) are connected by pointers. Each node contains data and a reference (link) to the next node.
Example:
Java
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(20);
System.out.println(head.data); // Output: 10
}
}
8. Searching Algorithms
Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Based on the type of search operation, these algorithms are generally classified into two categories: Sequential/ Linear Search or Interval Search.
Example (Linear Search):
Java
// Java program to implement Linear Search
class GfG {
public static void main(String args[]) {
int arr[] = { 2, 3, 4, 10, 40 };
int x = 50; // Element to search
int n = arr.length;
for (int i = 0; i <= n; i++)
{ if( i == n )
{ System.out.print("Element is not present");
break;
}
if (arr[i] == x)
{ System.out.print("Element is present"
+ " at index "
+ i);
break;
}
}
}
}
9. Sorting Algorithms
Sorting Algorithm are used to rearrange a given array or list of elements in an order. Sorting is provided in library implementation of most of the programming languages.
Example:
Java
// Java Program to sort an array
class GFG {
// Main driver method
public static void main(String[] args)
{// Custom input array
int arr[] = { 4, 3, 2, 1 };
// Outer loop
for (int i = 0; i < arr.length; i++) {
// Inner nested loop pointing 1 index ahead
for (int j = i + 1; j < arr.length; j++) {
// Checking elements
int temp = 0;
if (arr[j] < arr[i]) {
// Swapping
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Printing sorted array elements
System.out.print(arr[i] + " ");
}
}}
10. Greedy Algorithm
Greedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. Examples of popular Greedy Algorithms are Fractional Knapsack, Dijkstra's algorithm, Kruskal's algorithm, Huffman coding and Prim's Algorithm
Java
// Java program to find minimum cost
// to reduce array size to 1,
import java.lang.*;
public class GFG {
// function to calculate the
// minimum cost
static int cost(int []a, int n)
{
int min = a[0];
// find the minimum using
// for loop
for(int i = 1; i< a.length; i++)
{
if (a[i] < min)
min = a[i];
}
// Minimum cost is n-1 multiplied
// with minimum element.
return (n - 1) * min;
}
// driver program to test the
// above function.
static public void main (String[] args)
{
int []a = { 4, 3, 2 };
int n = a.length;
System.out.println(cost(a, n));
}
}
// This code is contributed by parashar.
11. Trees
Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. Where the topmost node of the tree is called the root, and the nodes below it are called the child nodes.
Example (Binary Search Tree):
Java
// java code for above approach
import java.io.*;
import java.util.*;
class GfG {
// Function to print the parent of each node
public static void
printParents(int node, Vector<Vector<Integer> > adj,
int parent)
{
// current node is Root, thus, has no parent
if (parent == 0)
System.out.println(node + "->Root");
else
System.out.println(node + "->" + parent);
// Using DFS
for (int i = 0; i < adj.get(node).size(); i++)
if (adj.get(node).get(i) != parent)
printParents(adj.get(node).get(i), adj,
node);
}
// Function to print the children of each node
public static void
printChildren(int Root, Vector<Vector<Integer> > adj)
{
// Queue for the BFS
Queue<Integer> q = new LinkedList<>();
// pushing the root
q.add(Root);
// visit array to keep track of nodes that have been
// visited
int vis[] = new int[adj.size()];
Arrays.fill(vis, 0);
// BFS
while (q.size() != 0) {
int node = q.peek();
q.remove();
vis[node] = 1;
System.out.print(node + "-> ");
for (int i = 0; i < adj.get(node).size(); i++) {
if (vis[adj.get(node).get(i)] == 0) {
System.out.print(adj.get(node).get(i)
+ " ");
q.add(adj.get(node).get(i));
}
}
System.out.println();
}
}
// Function to print the leaf nodes
public static void
printLeafNodes(int Root, Vector<Vector<Integer> > adj)
{
// Leaf nodes have only one edge and are not the
// root
for (int i = 1; i < adj.size(); i++)
if (adj.get(i).size() == 1 && i != Root)
System.out.print(i + " ");
System.out.println();
}
// Function to print the degrees of each node
public static void
printDegrees(int Root, Vector<Vector<Integer> > adj)
{
for (int i = 1; i < adj.size(); i++) {
System.out.print(i + ": ");
// Root has no parent, thus, its degree is
// equal to the edges it is connected to
if (i == Root)
System.out.println(adj.get(i).size());
else
System.out.println(adj.get(i).size() - 1);
}
}
// Driver code
public static void main(String[] args)
{
// Number of nodes
int N = 7, Root = 1;
// Adjacency list to store the tree
Vector<Vector<Integer> > adj
= new Vector<Vector<Integer> >();
for (int i = 0; i < N + 1; i++) {
adj.add(new Vector<Integer>());
}
// Creating the tree
adj.get(1).add(2);
adj.get(2).add(1);
adj.get(1).add(3);
adj.get(3).add(1);
adj.get(1).add(4);
adj.get(4).add(1);
adj.get(2).add(5);
adj.get(5).add(2);
adj.get(2).add(6);
adj.get(6).add(2);
adj.get(4).add(7);
adj.get(7).add(4);
// Printing the parents of each node
System.out.println("The parents of each node are:");
printParents(Root, adj, 0);
// Printing the children of each node
System.out.println(
"The children of each node are:");
printChildren(Root, adj);
// Printing the leaf nodes in the tree
System.out.println(
"The leaf nodes of the tree are:");
printLeafNodes(Root, adj);
// Printing the degrees of each node
System.out.println("The degrees of each node are:");
printDegrees(Root, adj);
}
}
// This code is contributed by rj13to.
12. Hashing
In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. In java there are various methods to implement hashing such as by using HashTable or HashMap etc.
Java
// Java program to demonstrate working of HashTable
import java.util.*;
class GFG {
public static void main(String args[])
{
// Create a HashTable to store
// String values corresponding to integer keys
Hashtable<Integer, String>
hm = new Hashtable<Integer, String>();
// Input the values
hm.put(1, "Geeks");
hm.put(12, "forGeeks");
hm.put(15, "A computer");
hm.put(3, "Portal");
// Printing the Hashtable
System.out.println(hm);
}
}
13. Dynamic Programming
Dynamic programming (DP) is used to solve problems by breaking them down into overlapping subproblems, solving each subproblem only once, and storing the results.
Java
// Java program to find fibonacci number using memoization.
import java.util.Arrays;
class GfG {
static int fibRec(int n, int[] memo) {
// Base case
if (n <= 1) return n;
// To check if output already exists
if (memo[n] != -1) return memo[n];
// Calculate and save output for future use
memo[n] = fibRec(n - 1, memo) + fibRec(n - 2, memo);
return memo[n];
}
public static void main(String[] args) {
int n = 9;
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
System.out.println( fibRec(n, memo));
}
}
14. Graphs
A graph consists of vertices connected by edges. It can be represented using adjacency matrices or adjacency lists.
Example (Graph Representation using Adjacency List):
Java
class Graph {
private LinkedList<Integer> adjList[];
Graph(int vertices) {
adjList = new LinkedList[vertices];
for (int i = 0; i < vertices; ++i)
adjList[i] = new LinkedList<>();
}
}
15. Backtracking Algorithm
Backtracking algorithms are like problem-solving strategies that help explore different options to find the best solution. They work by trying out different paths and if one doesn't work, they backtrack and try another until they find the right one.
Example:
Java
// Java program to print all subsets
// of a given Set or Array using backtracking
import java.util.*;
class GfG {
static void subsetRecur(int i, int[] arr,
List<List<Integer>> res, List<Integer> subset) {
// add subset at end of array
if (i == arr.length) {
res.add(new ArrayList<>(subset));
return;
}
// include the current value and
// recursively find all subsets
subset.add(arr[i]);
subsetRecur(i + 1, arr, res, subset);
// exclude the current value and
// recursively find all subsets
subset.remove(subset.size() - 1);
subsetRecur(i + 1, arr, res, subset);
}
static List<List<Integer>> subsets(int[] arr) {
List<Integer> subset = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
subsetRecur(0, arr, res, subset);
return res;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3};
List<List<Integer>> res = subsets(arr);
for (List<Integer> subset : res) {
for (int num : subset) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
16. Bitwise Algorithms
Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers by using operators like AND, OR, XOR, NOT, Left Sift and Right Shift.
Java
// Java program to unset the rightmost
// set bit using Naive approach
class GfG {
// Unsets the rightmost set bit
// of n and returns the result
static int unsetLSB(int n) {
if (n == 0)
return 0;
// Find the rightmost set bit
int pos = 0;
while (((n >> pos) & 1) == 0) {
pos++;
}
// Unset the rightmost set bit
n = n ^ (1 << pos);
return n;
}
public static void main(String[] args) {
int n = 12;
System.out.print(unsetLSB(n));
}
}
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem