Data Structures and Algorithms
Data Structures and Algorithms
Data Structures and Algorithms (DSA) are crucial for writing efficient and optimized code. Understanding
DSA in Java can significantly enhance your problem-solving skills and performance in technical
interviews. Here’s a detailed overview:
Data Structures are ways to organize and store data so that it can be accessed and modified efficiently.
Algorithms are step-by-step procedures or formulas for solving problems. Together, they form the
backbone of computer science and programming.
1. Arrays
o Example:
2. Linked Lists
o Definition: A linear data structure where elements are stored in nodes, with each node
pointing to the next.
o Types: Singly Linked List, Doubly Linked List, Circular Linked List.
o Example:
o class Node {
o int data;
o Node next;
o }
3. Stacks
o Example:
o stack.push(1);
o stack.push(2);
4. Queues
o Example:
o queue.add(1);
o queue.add(2);
5. Trees
o Definition: A hierarchical data structure with a root node and child nodes.
o Types: Binary Tree, Binary Search Tree (BST), AVL Tree, Red-Black Tree.
o Example:
o class TreeNode {
o int data;
o }
6. Graphs
o Example:
o class Graph {
o private int V;
o Graph(int v) {
o V = v;
o adj = new LinkedList[v];
o }
o }
1. Sorting Algorithms
o int n = arr.length;
o arr[j] = arr[j+1];
o arr[j+1] = temp;
o }
o }
o int i = (low-1);
o i++;
o arr[i] = arr[j];
o arr[j] = temp;
o }
o }
o arr[i+1] = arr[high];
o arr[high] = temp;
o return i+1;
o }
o }
o }
2. Search Algorithms
o int n = arr.length;
o if (arr[i] == x)
o return i;
o }
o return -1;
o }
o int l = 0, r = arr.length - 1;
o while (l <= r) {
o int m = l + (r - l) / 2;
o if (arr[m] == x)
o return m;
o if (arr[m] < x)
o l = m + 1;
o else
o r = m - 1;
o }
o return -1;
o }
3. Graph Algorithms
o visited[v] = true;
o Iterator<Integer> i = adj[v].listIterator();
o while (i.hasNext()) {
o int n = i.next();
o if (!visited[n])
o DFS(n, visited);
o }
o }
o void BFS(int s) {
o visited[s] = true;
o queue.add(s);
o while (queue.size() != 0) {
o s = queue.poll();
o Iterator<Integer> i = adj[s].listIterator();
o while (i.hasNext()) {
o int n = i.next();
o if (!visited[n]) {
o visited[n] = true;
o queue.add(n);
o }
o }
o }
o }
4. Complexity Analysis
Understanding the time and space complexity of algorithms is crucial for writing efficient code. The Big O
notation is commonly used to describe the performance of an algorithm.
Time Complexity: Measures the time an algorithm takes to complete as a function of the input
size.
Space Complexity: Measures the amount of memory an algorithm uses as a function of the
input size.
5. Practical Applications
6. Learning Resources