LAB MANUAL
Advance Data Structure & Algorithm
Submitted To:- Name:- Vaibhav Kholia
Dr. Subash Chandra Gupta Section:- 06
Admission no:- 22SCSE1410017
Course:- B.tech (CSE)
GALGOTIAS
{under the Utter Pradesh Private Universities Act No, 12 of 2019}
SUBJECT Advance Data Structure & PROGRAMM B. Tech.
Algorithm
SUBJECT CODE IUC503B SEMESTER 5
DURATION OF
CREDITS 13 Weeks
SEMESTER
PREREQUISITE
Knowledge of computer and SESSION
SUBJECVS 2 Hrs per Week
DURATION
Basic Programming
Vision
"To be recognized globally as a premier School of Computing Science and
Engineering for imparting quality and value-based education within a
multidisciplinary and collaborative research-based environment.
Mission
The mission of the school is to:
Ml: Develop a strong foundation in fundamentals of computing science and
engineering with responsiveness towards emerging technologies.
M2: Establish state-of-the-art facilities and adopt education 4.0 practices to
analyze, develop, test and deploy sustainable ethical IT solutions by involving
multiple stakeholders
1. Find Maximum and Minimum Elements in an Array
public class ArrayProblems { public
static int[] findMinMax(int[] arr) { int
min = arr[0], max = arr[0]; for (int
num : arr) { if (num < min) min =
num; if (num > max) max = num;
return new int[]{min, max};
2. Reverse an Array
public static void reverseArray(int[] arr) {
int start = 0, end = arr.length - 1; while
(start < end) { int temp = arr[start];
arr[start] = arr[end]; arr[end] =
temp; start++; end--;
3. Find Kth Smallest/Largest Element
public static int findKthElement(int[] arr, int k, boolean isLargest) {
java.util.Arrays.sort(arr); return isLargest ? arr[arr.length - k] :
arr[k - 1];
4. Sort Array of 0s, 1s, and 2s public static void
sortZeroOneTwo(int[] arr) { int low = 0,
mid = 0, high = arr.length - 1; while (mid
<= high) { if (arr[mid] == 0) {
int temp = arr[low]; arr[low++] =
arr[mid]; arr[mid++] = temp;
} else if (arr[mid] == 1) { mid++;
} else { int temp = arr[mid];
arr[mid] = arr[high]; arr[high--] =
temp;
5. Move All Zeroes to End public static void
moveZeroesToEnd(int[] arr) { int index =
0; for (int num : arr) { if (num != 0)
arr[index++] = num;
while (index < arr.length) arr[index++] = 0;
6. Reverse a Linked List
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
public static ListNode reverseLinkedList(ListNode head) {
ListNode prev = null; while (head != null) {
ListNode next = head.next; head.next = prev;
prev = head; head = next;
return prev;
}
7. Detect Cycle in a Linked List public static
boolean hasCycle(ListNode head) { ListNode
slow = head, fast = head; while (fast != null &&
fast.next != null) { slow = slow.next;
fast = fast.next.next; if (slow == fast) return
true;
return false;
8. Find Middle of Linked List public static
ListNode findMiddle(ListNode head) { ListNode
slow = head, fast = head; while (fast != null &&
fast.next != null) { slow = slow.next;
fast = fast.next.next;
return slow;
9. Merge Two Sorted Linked Lists public
static ListNode mergeSortedLists(ListNode l1,
ListNode l2) { ListNode dummy = new
ListNode(0), tail = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) { tail.next
= l1; l1 = l1.next; }
else { tail.next = l2;
l2 = l2.next;
} tail =
tail.next;
}
tail.next = (l1 != null) ? l1 : l2;
return dummy.next;
10. Remove Nth Node from End public static ListNode
removeNthFromEnd(ListNode head, int n) { ListNode dummy =
new ListNode(0); dummy.next = head;
ListNode first = dummy, second = dummy;
for (int i = 0; i <= n; i++) first = first.next;
while (first != null) { first = first.next;
second = second.next;
second.next = second.next.next;
return dummy.next;
public static void main(String[] args) {
int[] array = {3, 1, 2, 5, 4}; int[]
minMax = findMinMax(array);
System.out.println("Min: " + minMax[0] + ", Max: " + minMax[1]);
reverseArray(array);
System.out.println("Reversed Array: " + java.util.Arrays.toString(array));
System.out.println("2nd Largest: " + findKthElement(array, 2, true));
11. Implement a Stack Using Arrays class
StackUsingArray {
private int[] stack;
private int top; private
int capacity;
public StackUsingArray(int capacity) {
this.capacity = capacity; stack =
new int[capacity];
top = -1;
public void push(int value) {
if (top == capacity - 1) {
System.out.println("Stack Overflow");
return;
stack[++top] = value;
public int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
return stack[top--];
public int peek() {
if (isEmpty()) {
System.out.println("Stack is Empty");
return -1;
return stack[top];
}
public boolean isEmpty() {
return top == -1;
12. Implement a Stack Using Linked List
class StackUsingLinkedList { private
static class Node { int data;
Node next;
Node(int data) { this.data = data; }
private Node top;
public void push(int value) {
Node newNode = new Node(value);
newNode.next = top; top =
newNode;
public int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
int value = top.data;
top = top.next; return
value;
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is Empty");
return -1;
return top.data;
public boolean isEmpty() {
return top == null;
13. Check for Balanced Parentheses public
static boolean isBalanced(String str) {
java.util.Stack<Character> stack = new
java.util.Stack<>(); for (char ch :
str.toCharArray()) { if (ch == '(' || ch ==
'{' || ch == '[') { stack.push(ch);
} else if (ch == ')' && !stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else if (ch == '}' && !stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else if (ch == ']' && !stack.isEmpty() && stack.peek() == '[') {
stack.pop(); } else { return false;
return stack.isEmpty();
}
14. Evaluate Postfix Expression public static int
evaluatePostfix(String expr) { java.util.Stack<Integer>
stack = new java.util.Stack<>(); for (char ch :
expr.toCharArray()) { if (Character.isDigit(ch)) {
stack.push(ch - '0');
} else { int b = stack.pop();
int a = stack.pop(); switch (ch) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(a / b); break;
return stack.pop();
15. Next Greater Element public static int[]
nextGreaterElement(int[] arr) { int[] result = new
int[arr.length]; java.util.Stack<Integer> stack = new
java.util.Stack<>();
for (int i = arr.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= arr[i]) {
stack.pop();
result[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
return result;
public static void main(String[] args) {
int[] array = {3, 1, 2, 5, 4};
int[] minMax = findMinMax(array);
System.out.println("Min: " + minMax[0] + ", Max: " + minMax[1]);
reverseArray(array);
System.out.println("Reversed Array: " + java.util.Arrays.toString(array));
System.out.println("2nd Largest: " + findKthElement(array, 2, true));
System.out.println("Balanced Parentheses: " + isBalanced("{[()]}"));
System.out.println("Postfix Evaluation: " + evaluatePostfix("231*+9-"));
System.out.println("Next Greater Element: " +
java.util.Arrays.toString(nextGreaterElement(array)));
16. Implement a Queue Using Arrays
class QueueUsingArray {
private int[] queue; private
int front, rear, capacity;
public QueueUsingArray(int capacity) {
this.capacity = capacity;
queue = new int[capacity];
front = rear = 0;
public void enqueue(int value) {
if (rear == capacity) {
System.out.println("Queue Overflow");
return;
queue[rear++] = value;
public int dequeue() {
if (front == rear) {
System.out.println("Queue Underflow");
return -1;
int value = queue[front++];
return value;
public int front() {
if (front == rear) {
System.out.println("Queue is Empty");
return -1;
return queue[front];
public boolean isEmpty() {
return front == rear;
public static void main(String[] args) {
int[] array = {3, 1, 2, 5, 4};
System.out.println("Balanced Parentheses: " + isBalanced("{[()]}"));
System.out.println("Postfix Evaluation: " + evaluatePostfix("231*+9-"));
System.out.println("Next Greater Element: " +
java.util.Arrays.toString(nextGreaterElement(array)));
QueueUsingArray queue = new QueueUsingArray(5);
queue.enqueue(10); queue.enqueue(20);
System.out.println("Front Element: " + queue.front());
queue.dequeue();
System.out.println("Front Element after Dequeue: " + queue.front());
17. Implement a Queue Using Linked List
class LinkedListQueue {
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
private Node front, rear;
public LinkedListQueue() {
this.front = this.rear = null;
public void enqueue(int data) {
Node newNode = new Node(data);
if (rear == null) {
front = rear = newNode;
return;
rear.next = newNode;
rear = newNode;
public int dequeue() {
if (front == null) {
throw new IllegalStateException("Queue is empty");
int data = front.data;
front = front.next;
if (front == null) {
rear = null;
return data;
public int front() {
if (front == null) {
throw new IllegalStateException("Queue is empty");
return front.data;
public boolean isEmpty() {
return front == null;
}
}
18. Implement a Circular Queue class
CircularQueue {
private int[] arr; private int front,
rear, size, capacity;
public CircularQueue(int capacity) {
this.capacity = capacity; this.arr
= new int[capacity]; this.front =
this.size = 0; this.rear = capacity -
1;
public boolean isFull() {
return size == capacity;
public boolean isEmpty() {
return size == 0;
public void enqueue(int data) {
if (isFull()) {
throw new IllegalStateException("Queue is full");
rear = (rear + 1) % capacity;
arr[rear] = data; size++;
}
public int dequeue() {
if (isEmpty()) { throw new
IllegalStateException("Queue is empty");
int data = arr[front];
front = (front + 1) % capacity;
size--;
return data;
public int front() { if (isEmpty()) { throw new
IllegalStateException("Queue is empty");
return arr[front];
public int rear() { if (isEmpty()) { throw new
IllegalStateException("Queue is empty");
return arr[rear];
19. Generate Binary Numbers from 1 to N import
java.util.*; class BinaryNumbers { public static
List<String> generateBinaryNumbers(int N) {
List<String> result = new ArrayList<>();
Queue<String> queue = new LinkedList<>();
queue.add("1");
for (int i = 0; i < N; i++) {
String current = queue.poll();
result.add(current);
queue.add(current + "0");
queue.add(current + "1");
return result;
20. Implement a Queue Using Two Stacks
class QueueUsingStacks {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void enqueue(int data) {
stack1.push(data);
public int dequeue() { if (stack1.isEmpty() &&
stack2.isEmpty()) { throw new
IllegalStateException("Queue is empty");
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
return stack2.pop();
}
public boolean isEmpty() { return
stack1.isEmpty() && stack2.isEmpty();
21. Implement a Binary Tree
class BinaryTree { static
class Node {
int data;
Node left, right;
Node(int data) { this.data
= data; this.left =
this.right = null; }
Node root;
public void insert(int data) {
root = insertRec(root, data);
private Node insertRec(Node root, int data) {
if (root == null) {
root = new Node(data);
return root;
if (data < root.data) { root.left =
insertRec(root.left, data); } else if (data >
root.data) { root.right =
insertRec(root.right, data);
}
return root;
public void inorderTraversal() {
inorderRec(root);
private void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
public void preorderTraversal() {
preorderRec(root);
private void preorderRec(Node root) {
if (root != null) {
System.out.print(root.data + " ");
preorderRec(root.left); preorderRec(root.right);
public void postorderTraversal() {
postorderRec(root);
private void postorderRec(Node root) {
if (root != null) {
postorderRec(root.left);
postorderRec(root.right);
System.out.print(root.data + " ");
22. Inorder Traversal of a Binary Tree
java Copy code
class BinaryTree {
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data; left
= right = null;
// Inorder traversal (Left, Root, Right)
public void inorder(Node root) {
if (root == null) {
return;
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
23. Preorder Traversal of a Binary Tree
java Copy code public void
preorder(Node root) {
if (root == null) {
return;
System.out.print(root.data + " ");
preorder(root.left); preorder(root.right);
24. Postorder Traversal of a Binary Tree
java
Copy code
public void postorder(Node root) {
if (root == null) {
return;
postorder(root.left);
postorder(root.right);
System.out.print(root.data + " ");
25. Level Order Traversal of a Binary Tree
java Copy code import
java.util.LinkedList; import
java.util.Queue;
public void levelOrder(Node root) {
if (root == null) {
return;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node current = queue.poll();
System.out.print(current.data + " ");
if (current.left != null) {
queue.add(current.left);
if (current.right != null) {
queue.add(current.right);
26. Height of a Binary Tree java
Copy code
public int height(Node root) {
if (root == null) {
return 0;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return Math.max(leftHeight, rightHeight) + 1;
27. Diameter of a Binary Tree java
Copy code public int diameter(Node
root) { return
diameterHelper(root).diameter;
private Result diameterHelper(Node root) {
if (root == null) { return new Result(0, 0);
// diameter, height
}
Result left = diameterHelper(root.left);
Result right = diameterHelper(root.right);
int height = Math.max(left.height, right.height) + 1;
int diameter = Math.max(left.height + right.height + 1,
Math.max(left.diameter, right.diameter));
return new Result(diameter, height);
static class Result {
int diameter; int
height;
Result(int diameter, int height) {
this.diameter = diameter; this.height
= height;
28. Check if a Binary Tree is Balanced java
Copy code public boolean
isBalanced(Node root) { return
checkHeight(root) != -1;
private int checkHeight(Node root) {
if (root == null) {
return 0;
}
int leftHeight = checkHeight(root.left);
if (leftHeight == -1) return -1;
int rightHeight = checkHeight(root.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
return Math.max(leftHeight, rightHeight) + 1;
29. Lowest Common Ancestor (LCA) of Two Nodes in a Binary Tree
java
Copy code public Node lowestCommonAncestor(Node root, Node
p, Node q) {
if (root == null || root == p || root == q) {
return root;
Node left = lowestCommonAncestor(root.left, p, q);
Node right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
return left != null ? left : right;
}
30. Implement Graph Using Adjacency List
java
Copy code
import java.util.*;
class Graph { private Map<Integer, List<Integer>>
adjacencyList; public Graph() { adjacencyList = new
HashMap<>();
public void addVertex(int vertex) {
adjacencyList.putIfAbsent(vertex, new ArrayList<>());
public void addEdge(int vertex1, int vertex2) {
adjacencyList.putIfAbsent(vertex1, new ArrayList<>());
adjacencyList.putIfAbsent(vertex2, new ArrayList<>());
adjacencyList.get(vertex1).add(vertex2);
adjacencyList.get(vertex2).add(vertex1);
public List<Integer> getNeighbors(int vertex) {
return adjacencyList.get(vertex);
31. Breadth-First Search (BFS) on a Graph
java
Copy code
public void bfs(Graph graph, int startVertex) {
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
visited.add(startVertex);
queue.add(startVertex);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for (int neighbor : graph.getNeighbors(vertex)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor); queue.add(neighbor);
32. Depth-First Search (DFS) on a Graph
java
Copy code
public void dfs(Graph graph, int vertex, Set<Integer> visited) {
if (visited.contains(vertex)) {
return;
visited.add(vertex);
System.out.print(vertex + " ");
for (int neighbor : graph.getNeighbors(vertex)) {
dfs(graph, neighbor, visited);
}
}
33. Detect Cycle in an Undirected Graph
java
Copy code public boolean
hasCycle(Graph graph) {
Set<Integer> visited = new HashSet<>();
for (int vertex : graph.adjacencyList.keySet()) {
if (!visited.contains(vertex)) { if
(hasCycleUtil(graph, vertex, visited, -1)) {
return true;
return false;
private boolean hasCycleUtil(Graph graph, int current, Set<Integer> visited, int parent) {
visited.add(current);
for (int neighbor : graph.getNeighbors(current)) {
if (!visited.contains(neighbor)) { if
(hasCycleUtil(graph, neighbor, visited, current)) {
return true;
} else if (neighbor != parent) {
return true; // Found a cycle
return false;
}
34. Connected Components in an Undirected Graph
java
Copy code public int
connectedComponents(Graph graph) {
Set<Integer> visited = new HashSet<>(); int
count = 0;
for (int vertex : graph.adjacencyList.keySet()) {
if (!visited.contains(vertex)) {
dfs(graph, vertex, visited); count++;
return count;
private void dfs(Graph graph, int vertex, Set<Integer> visited) {
visited.add(vertex); for (int neighbor :
graph.getNeighbors(vertex)) { if
(!visited.contains(neighbor)) { dfs(graph, neighbor,
visited);
35. Find MST Using Kruskal's Algorithm
java
Copy code
import java.util.*;
class Edge implements Comparable<Edge> {
int u, v, weight;
Edge(int u, int v, int weight) {
this.u = u; this.v
= v; this.weight =
weight;
public int compareTo(Edge other) {
return this.weight - other.weight;
public List<Edge> kruskalMST(Graph graph) { List<Edge> edges = new ArrayList<>();
for (int vertex : graph.adjacencyList.keySet()) { for (int neighbor :
graph.getNeighbors(vertex)) { edges.add(new Edge(vertex, neighbor, 1)); //
Assuming weight is 1 for simplicity
Collections.sort(edges);
DisjointSet ds = new DisjointSet(graph.adjacencyList.size());
List<Edge> mst = new ArrayList<>();
for (Edge edge : edges) { if
(ds.find(edge.u) != ds.find(edge.v)) {
mst.add(edge); ds.union(edge.u,
edge.v);
return mst;
}
class DisjointSet { int[]
parent, rank;
DisjointSet(int size)
{ parent = new
int[size]; rank =
new int[size];
for (int i = 0; i < size;
i++) {
parent[i] = i;
int find(int i) { if (parent[i]
!= i) { parent[i] =
find(parent[i]);
return parent[i];
void union(int x, int y) { int rootX =
find(x); int rootY = find(y); if
(rootX != rootY) { if (rank[rootX] >
rank[rootY]) { parent[rootY] =
rootX; } else if (rank[rootX] <
rank[rootY]) { parent[rootX] =
rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
36. Find MST Using Prim's Algorithm
java
Copy code import
java.util.*;
public List<Edge> primMST(Graph graph, int startVertex) {
Set<Integer> visited = new HashSet<>();
PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.weight));
List<Edge> mst = new ArrayList<>();
visited.add(startVertex); for (int neighbor : graph.getNeighbors(startVertex)) {
pq.add(new Edge(startVertex, neighbor, 1)); // Assuming weight is 1 for simplicity
while (!pq.isEmpty()) {
Edge edge = pq.poll(); if
(!visited.contains(edge.v)) {
visited.add(edge.v);
mst.add(edge);
for (int neighbor : graph.getNeighbors(edge.v)) { if
(!visited.contains(neighbor)) { pq.add(new Edge(edge.v, neighbor, 1)); //
Assuming weight is 1 for simplicity
}
return mst;
37. Fibonacci Sequence (Dynamic Programming)
java Copy
code
public int fibonacci(int n) {
if (n <= 1) {
return n;
int[] dp = new int[n + 1];
dp[0] = 0; dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
return dp[n];
38. Climbing Stairs (Distinct Ways)
java Copy code
public int climbStairs(int n) {
if (n <= 1) {
return 1;
int[] dp = new int[n + 1];
dp[0] = 1; dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
39. Min Cost Climbing Stairs java
Copy code
public int minCostClimbingStairs(int[] cost) {
int n = cost.length; int[] dp = new int[n];
dp[0] = cost[0]; dp[1] = cost[1];
for (int i = 2; i < n; i++) { dp[i] = cost[i] +
Math.min(dp[i - 1], dp[i - 2]);
return Math.min(dp[n - 1], dp[n - 2]);
40. House Robber
java
Copy code
public int rob(int[] nums) {
if (nums.length == 0) {
return 0;
int[] dp = new int[nums.length];
dp[0] = nums[0]; dp[1] =
Math.max(nums[0], nums[1]);
for (int i = 2; i < nums.length; i++) { dp[i] =
Math.max(dp[i - 1], dp[i - 2] + nums[i]);
return dp[nums.length - 1];
}
41. Maximum Subarray Sum (Kadane’s Algorithm)
java
Copy code public int
maxSubArray(int[] nums) { int
maxSum = nums[0]; int
currentSum = nums[0];
for (int i = 1; i < nums.length; i++) { currentSum =
Math.max(nums[i], currentSum + nums[i]); maxSum =
Math.max(maxSum, currentSum);
return maxSum;
42. Activity Selection java
Copy code
class Activity {
int start, end;
Activity(int start, int end) {
this.start = start; this.end
= end;
public int selectActivities(Activity[] activities) {
Arrays.sort(activities, Comparator.comparingInt(a -> a.end)); int count = 1; int lastEnd =
activities[0].end;
for (int i = 1; i < activities.length; i++) {
if (activities[i].start >= lastEnd) {
count++; lastEnd =
activities[i].end;
return count;
43. Fractional Knapsack Problem java
Copy code
class Item { int
value, weight;
Item(int value, int weight) {
this.value = value; this.weight
= weight;
public double fractionalKnapsack(int W, Item[] items) {
Arrays.sort(items, (a, b) -> (b.value * 100 / b.weight) - (a.value * 100 / a.weight));
double maxValue = 0;
for (Item item : items) {
if (W == 0) break;
int takeWeight = Math.min(W, item.weight); maxValue
+= takeWeight * (double) item.value / item.weight;
W -= takeWeight;
}
return maxValue;
44. Huffman Coding
import java.util.*;
class HuffmanNode {
char ch;
int freq;
HuffmanNode left, right;
HuffmanNode(char ch, int freq) {
this.ch = ch;
this.freq = freq; left
= right = null;
class HuffmanCoding { public
void encode(String text) {
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char ch : text.toCharArray()) { frequencyMap.put(ch,
frequencyMap.getOrDefault(ch, 0) + 1);
PriorityQueue<HuffmanNode> pq = new PriorityQueue<>(Comparator.comparingInt(n ->
n.freq));
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
pq.add(new HuffmanNode(entry.getKey(), entry.getValue()));
}
while (pq.size() > 1) {
HuffmanNode left = pq.poll();
HuffmanNode right = pq.poll();
HuffmanNode merged = new HuffmanNode('\0', left.freq + right.freq);
merged.left = left;
merged.right = right;
pq.add(merged);
HuffmanNode root = pq.poll();
Map<Character, String> huffmanCodes = new HashMap<>();
generateCodes(root, "", huffmanCodes);
// Print Huffman Codes for (Map.Entry<Character, String> entry
: huffmanCodes.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
private void generateCodes(HuffmanNode root, String code, Map<Character, String>
huffmanCodes) {
if (root == null) return;
if (root.left == null && root.right == null) {
huffmanCodes.put(root.ch, code);
generateCodes(root.left, code + "0", huffmanCodes);
generateCodes(root.right, code + "1", huffmanCodes);
}
public static void main(String[] args) {
String text = "this is an example for huffman encoding";
HuffmanCoding huffman = new HuffmanCoding();
huffman.encode(text);
45. Job Sequencing Problem import
java.util.*;
class Job { int id,
deadline, profit;
Job(int id, int deadline, int profit) {
this.id = id;
this.deadline = deadline;
this.profit = profit;
class JobSequencing { public List<Job>
jobSequencing(Job[] jobs) {
Arrays.sort(jobs, (a, b) -> b.profit - a.profit); // Sort jobs by profit in descending order
int n = jobs.length;
boolean[] slot = new boolean[n];
List<Job> result = new ArrayList<>();
for (Job job : jobs) { // Find a slot for this job
for (int j = Math.min(n - 1, job.deadline - 1); j >= 0; j--) {
if (!slot[j]) {
slot[j] = true;
result.add(job);
break;
return result;
public static void main(String[] args) {
Job[] jobs = { new Job(1, 4, 20),
new Job(2, 1, 10), new Job(3, 1,
40), new Job(4, 1, 30)
};
JobSequencing js = new JobSequencing();
List<Job> result = js.jobSequencing(jobs);
System.out.println("Job Sequence with Maximum Profit:");
for (Job job : result) {
System.out.println("Job ID: " + job.id + ", Profit: " + job.profit);
46. Minimum Number of Coins
java
Copy code public int minCoins(int[] coins,
int amount) { int[] dp = new int[amount +
1]; Arrays.fill(dp, amount + 1); dp[0] =
0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) { if (i -
coin >= 0) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
return dp[amount] > amount ? -1 : dp[amount];
47. N-Queens Problem
import java.util.*;
class NQueens { private static final int N = 4; // You can
change N to any value
public boolean solveNQueens() { int[] board = new int[N]; // board[i] represents the
column where the queen is placed in row i if (placeQueens(board, 0)) {
printSolution(board); return true;
} else {
System.out.println("Solution does not exist.");
return false;
private boolean placeQueens(int[] board, int row) {
if (row == N) { return true; // All
queens are placed
}
for (int col = 0; col < N; col++) {
if (isSafe(board, row, col)) {
board[row] = col; if
(placeQueens(board, row + 1)) {
return true;
board[row] = -1; // Backtrack
return false; // No valid placement found
private boolean isSafe(int[] board, int row, int col) {
for (int i = 0; i < row; i++) {
// Check if the queen is in the same column or diagonals if
(board[i] == col || Math.abs(board[i] - col) == Math.abs(i - row)) {
return false;
return true;
private void printSolution(int[] board) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i] == j) {
System.out.print("Q ");
} else {
System.out.print(". ");
}
System.out.println();
public static void main(String[] args) {
NQueens nQueens = new NQueens();
nQueens.solveNQueens();
48. Permutations java
Copy code public List<List<Integer>>
permute(int[] nums) { List<List<Integer>>
result = new ArrayList<>(); backtrack(nums,
new ArrayList<>(), result); return result;
private void backtrack(int[] nums, List<Integer> current, List<List<Integer>> result) {
if (current.size() == nums.length) { result.add(new ArrayList<>(current));
return;
for (int i = 0; i < nums.length; i++) { if
(current.contains(nums[i])) continue;
current.add(nums[i]); backtrack(nums,
current, result);
current.remove(current.size() - 1);
}
49. Subsets java
Copy code public List<List<Integer>>
subsets(int[] nums) { List<List<Integer>>
result = new ArrayList<>(); backtrack(nums,
0, new ArrayList<>(), result); return result;
private void backtrack(int[] nums, int index, List<Integer> current, List<List<Integer>> result) {
result.add(new ArrayList<>(current));
for (int i = index; i < nums.length; i++) {
current.add(nums[i]); backtrack(nums,
i + 1, current, result);
current.remove(current.size() - 1);