0% found this document useful (0 votes)
21 views43 pages

Lab Experiment ADSA - 22SCSE1180071

Advanced data structure and algorithms lab file

Uploaded by

jaatkushaljakhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views43 pages

Lab Experiment ADSA - 22SCSE1180071

Advanced data structure and algorithms lab file

Uploaded by

jaatkushaljakhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Advance Data Structure & Algorithm

Course Code: R1UC503B

Lab File
For
BACHELOR OF

ENGINEERING & TECHNOLOGY

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

GALGOTIAS UNIVERSITY, GREATER NOIDA

UTTAR PRADESH

Student Name: Kushal

Admission No: 22SCSE 1180071

Semester: 1

1 |P a g e
Lab Experiment
- ADSA (Advance data structures)
NAME :GAURAV KUMAR
22SCSE1420035
B.TECH CSE DATA SCIENCE

1.Find the Maximum and Minimum Elements in an Array: Write a function to find the maximum
and minimum elements in an array
:

public classMaxMinInArray {

public static void findMaxMin(int[] array) {

if (array == null || array.length == 0) {

System.out.println("Array is empty or null.");

return;

int max = array[0];

int min = array[0];

for (int i = 1; i < array.length; i++) {

if (array[i] > max) {

max = array[i];

if (array[i] < min) {

min = array[i];

System.out.println("Maximum Element: " + max);

System.out.println("Minimum Element: " + min);

public static void main(String[] args) {

int[] array = {12, 34, 5, 9, 78, -0,


5, 45};

findMaxMin(array);

2.Reverse an Array:
public class ReverseArray {
public static void reverseArray(int[] array) {

if (array == null || array.length <= 1) {

System.out.println("Array is null or too small to reverse.");

return;

int start = 0;

int end = array.length - 1;

while (start < end) {

// Swap the elements at start and end

int temp = array[start];

array[start] = array[end];

array[end] = temp;

// Move the pointers

start++;

end--;

public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5, 6, 7};

System.out.println("Original Array:");

printArray(array);

reverseArray(array);

System.out.println("Reversed Array:");

printArray(array);
}

// Helper method to print the array

public static void printArray(int[] array) {

for (int num : array) {

System.out.print(num + " ");

System.out.println();

3.Find the Kth Smallest/Largest Element in an Array: Write a function to find the Kth smallest

or largest element in an array:

.import java.util.Arrays; public

class KthElementFinder {

// Function to find the Kth smallest element public

static int findKthSmallest(int[] array, int k) { if (array ==

null || k <= 0 || k > array.length) { throw new

IllegalArgumentException("Invalid input");

Arrays.sort(array); // Sort the array in ascending order

return array[k - 1]; // Kth smallest element is at index k-1

// Function to find the Kth largest element public static

int findKthLargest(int[] array, int k) { if (array == null || k

<= 0 || k > array.length) { throw new

IllegalArgumentException("Invalid input");

}
Arrays.sort(array); // Sort the array in ascending order

return array[array.length - k]; // Kth largest element is at index (length-k)

public static void main(String[] args) {

int[] array = {7, 10, 4, 3, 20, 15}; int

k = 3;

System.out.println("Original Array: " + Arrays.toString(array));

int kthSmallest = findKthSmallest(array, k);

System.out.println(k + "rd Smallest Element: " + kthSmallest);

int kthLargest = findKthLargest(array, k);

System.out.println(k + "rd Largest Element: " + kthLargest);

4. Sort an Array of 0s, 1s, and 2s: Given an array containing only 0s, 1s, and 2s, sort the array in
linear time:

public class SortArray012 {

public static void sortArray(int[] array) { if (array == null ||

array.length <= 1) { return; // No need to sort if array is null

or has one element

int low = 0; // Pointer for 0s int

mid = 0; // Pointer for 1s int high =

array.length - 1; // Pointer for 2s


while (mid <= high) {

switch (array[mid])

{ case 0: // Swap

array[low] and array[mid], and

move both pointers

int temp0 = array[low];

array[low] = array[mid];

array[mid] = temp0;

low++; mid++;

break;

case 1: // Move mid pointer

mid++;

break;

case 2: // Swap array[mid] and array[high], and move high pointer

int temp2 = array[mid]; array[mid] = array[high];

array[high] = temp2;

high--;

break;

public static void main(String[] args)

{ int[] array = {0, 1, 2, 1, 0, 2, 1, 2, 0, 1,

0};

System.out.println("Original Array:");

printArray(array);

sortArray(array);
System.out.println("Sorted Array:");

printArray(array);

// Helper method to print the array

public static void printArray(int[] array) {

for (int num : array) {

System.out.print(num + " ");

System.out.println();

5. Move All Zeroes to End of Array:

public class MoveZeroes { public static

void moveZeroes(int[] nums) { int

nonZeroIndex = 0;

// Move all non-zero elements to the front

for (int i = 0; i < nums.length; i++) { if

(nums[i] != 0) { nums[nonZeroIndex+

+] = nums[i];

// Fill remaining elements with zeroes for

(int i = nonZeroIndex; i < nums.length; i++)

{ nums[i] = 0;

}
}

6. Reverse a Linked List:

class ListNode {

int val;

ListNode next;

ListNode(int x) { val = x; }

public class ReverseLinkedList { public

ListNode reverseList(ListNode head) {

ListNode prev = null; ListNode

current = head; while (current !=

null) { ListNode nextTemp =

current.next; current.next = prev;

prev = current; current =

nextTemp;

return prev;

7. Detect a Cycle in a Linked List:

java Copy code public class CycleDetection

{ public boolean hasCycle(ListNode head)

{ if (head == null) return false;

ListNode slow = head;

ListNode fast = head;

while (fast != null && fast.next != null) {

slow = slow.next; fast =


fast.next.next; if (slow == fast) return

true;

return false;

8. Find the Middle of a Linked List: public class

MiddleOfLinkedList { public ListNode

middleNode(ListNode head) {

ListNode slow = head;

ListNode fast = head;

while (fast != null && fast.next != null) {

slow = slow.next; fast =

fast.next.next;

return slow;

9. Merge Two Sorted Linked Lists: public class

MergeSortedLists { public ListNode

mergeTwoLists(ListNode l1, ListNode l2) {

ListNode dummy = new ListNode(0);

ListNode current = dummy;

while (l1 != null && l2 != null) {

if (l1.val < l2.val)

{ current.next = l1;

l1 = l1.next; } else
{ current.next = l2;

l2 = l2.next;

current = current.next;

if (l1 != null) current.next = l1;

if (l2 != null) current.next = l2;

return dummy.next;

10. Remove Nth Node from End of List: public class

RemoveNthFromEnd { public ListNode

removeNthFromEnd(ListNode head, int n) { ListNode

dummy = new ListNode(0); dummy.next = head;

ListNode fast = dummy;

ListNode slow = dummy;

for (int i = 1; i <= n + 1; i++) {

fast = fast.next;

while (fast != null) {

slow = slow.next; fast

= fast.next;

slow.next = slow.next.next;
return dummy.next;

11. Implement a Stack Using Arrays/Lists:

import java.util.ArrayList; public

class StackUsingArrayList

{ private ArrayList<Integer>

stack; public

StackUsingArrayList() { stack =

new ArrayList<>();

public void push(int x)

{ stack.add(x);

public int pop() { if (isEmpty()) { throw new

IllegalStateException("Stack is empty");

return stack.remove(stack.size() - 1);

public int peek() { if (isEmpty()) { throw new

IllegalStateException("Stack is empty");

return stack.get(stack.size() - 1);

public boolean isEmpty()

{ return stack.isEmpty();

}
12. Implement a Stack Using Linked List:

public class StackUsingLinkedList

{ private static class ListNode {

int val;

ListNode next;

ListNode(int x) { val = x; }

private ListNode top; public

StackUsingLinkedList() {

top = null;

public void push(int x) {

ListNode newNode = new ListNode(x);

newNode.next = top; top = newNode;

public int pop() { if (isEmpty()) { throw new

IllegalStateException("Stack is empty");

int value = top.val;

top = top.next; return

value;

public int peek() { if (isEmpty()) { throw new

IllegalStateException("Stack is empty");

return top.val;

}
public boolean isEmpty() { return

top == null;

13. Check for Balanced Parentheses:

import java.util.Stack;

public class BalancedParentheses

{ public boolean isBalanced(String s) {

Stack<Character> stack = new Stack<>();

for (char c : s.toCharArray()) {

if (c == '(' || c == '[' || c == '{') {

stack.push(c);

} else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') {

stack.pop();

} else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') {

stack.pop();

} else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') {

stack.pop(); } else { return false;

return stack.isEmpty();

14. Evaluate Postfix Expression:

import java.util.Stack;
public class PostfixEvaluation { public

int evaluatePostfix(String exp) {

Stack<Integer> stack = new Stack<>();

for (char c : exp.toCharArray()) { if

(Character.isDigit(c)) { stack.push(c - '0'); //

Push the number to stack

} else { int b = stack.pop();

int a = stack.pop(); switch (c) {

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:

import java.util.Stack; import

java.util.HashMap;

public class NextGreaterElement { public

int[] nextGreaterElement(int[] nums) {

Stack<Integer> stack = new Stack<>();

HashMap<Integer, Integer> map = new HashMap<>();


for (int num : nums) { while (!

stack.isEmpty() && stack.peek() < num)

{ map.put(stack.pop(), num);

stack.push(num);

for (int i = 0; i < nums.length; i++)

{ nums[i] = map.getOrDefault(nums[i], -

1);

return nums;

16. Implement a Queue Using Arrays/Lists:

import java.util.LinkedList;

public class QueueUsingArrayList

{ private LinkedList<Integer> queue;

public QueueUsingArrayList()

{ queue = new LinkedList<>();

public void enqueue(int x)

{ queue.addLast(x);

}
public int dequeue() { if (isEmpty()) { throw

new IllegalStateException("Queue is empty");

return queue.removeFirst();

public int front() { if (isEmpty()) { throw new

IllegalStateException("Queue is empty");

return queue.getFirst();

public boolean isEmpty()

{ return queue.isEmpty();

17. Implement a Queue Using Linked List:

public class QueueUsingLinkedList

{ private static class ListNode {

int val;

ListNode next;

ListNode(int x) { val = x; }

private ListNode front, rear;

public QueueUsingLinkedList()

{ front = rear = null;

}
public void enqueue(int x)

{ ListNode newNode = new

ListNode(x);

if (rear == null)

{ front = rear =

newNode;

return;

rear.next = newNode;

rear = newNode;

public int dequeue() { if (isEmpty()) { throw

new IllegalStateException("Queue is empty");

int value = front.val;

front = front.next; if (front

== null) rear = null; return

value;

public int front() { if (isEmpty()) { throw new

IllegalStateException("Queue is empty");

return front.val;

public boolean isEmpty()

{ return front == null;

}
}

18. Implement a Circular Queue:

public class CircularQueue { private

int[] queue; private int front, rear,

size, capacity;

public CircularQueue(int capacity) {

this.capacity = capacity;

this.queue = new int[capacity];

this.front = this.rear = this.size = 0;

public boolean enqueue(int x) {

if (isFull()) return false;

queue[rear] = x; rear =

(rear + 1) % capacity; size+

+; return true;

public int dequeue() { if

(isEmpty()) return -1; int

value = queue[front]; front =

(front + 1) % capacity;

size--;

return value;

public int front() { if

(isEmpty()) return -1;

return queue[front];
}

public int rear() { if (isEmpty()) return -1;

return queue[(rear - 1 + capacity) % capacity];

public boolean isEmpty()

{ return size == 0;

public boolean isFull()

{ return size == capacity;

19. Generate Binary Numbers from 1 to N Using a Queue:

import java.util.LinkedList;

public class BinaryNumbers { public void

generateBinaryNumbers(int n)

{ LinkedList<String> queue = new

LinkedList<>(); queue.add("1");

for (int i = 1; i <= n; i++) {

String current = queue.poll();

System.out.println(current);

queue.add(current + "0"); queue.add(current

+ "1");

20. Implement a Queue Using Stacks:


import java.util.Stack;

public class QueueUsingStacks

{ private Stack<Integer> stack1,

stack2;

public QueueUsingStacks() {

stack1 = new Stack<>();

stack2 = new Stack<>();

public void enqueue(int x)

{ stack1.push(x);

public int dequeue() { if (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:

public class BinaryTree

{ class TreeNode {

int val;

TreeNode left, right;

TreeNode(int x) { val = x; }

private TreeNode root;

public BinaryTree() {

root = null;

public void insert(int val)

{ root = insertRecursive(root,

val);

private TreeNode insertRecursive(TreeNode root, int val) {

if (root == null)

{ return new

TreeNode(val);

if (val < root.val) { root.left =

insertRecursive(root.left, val);

} else if (val > root.val) { root.right =

insertRecursive(root.right, val);

return root;
}

public void inorder()

{ inorderRecursive(root);

private void inorderRecursive(TreeNode root) {

if (root != null)

{ inorderRecursive(root.left);

System.out.print(root.val + " ");


inorderRecursive(root.right);

22. Inorder Traversal: public void

inorderTraversal(TreeNode root) {

if (root != null)

{ inorderTraversal(root.left);

System.out.print(root.val + " ");

inorderTraversal(root.right);

23. Preorder Traversal: public void

preorderTraversal(TreeNode root) {

if (root != null) {

System.out.print(root.val + " ");

preorderTraversal(root.left);

preorderTraversal(root.right);

}
24. Postorder Traversal: public void

postorderTraversal(TreeNode root) {

if (root != null)

{ postorderTraversal(root.left);

postorderTraversal(root.right);

System.out.print(root.val + " ");

25. Level Order Traversal: import

java.util.LinkedList; import java.util.Queue;

public void levelOrderTraversal(TreeNode

root) { if (root == null) return;

Queue<TreeNode> queue = new LinkedList<>();

queue.add(root);

while (!queue.isEmpty()) {

TreeNode node = queue.poll();

System.out.print(node.val + " ");

if (node.left != null) queue.add(node.left);

if (node.right != null) queue.add(node.right);

26. Height of a Binary Tree: public class

BinaryTree { class TreeNode {

int val;

TreeNode left, right;

TreeNode(int x) { val = x; }

}
public int height(TreeNode 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: public

class BinaryTree {

class TreeNode {

int val;

TreeNode left, right;

TreeNode(int x) { val = x; }

public int diameter(TreeNode root) { int[] maxDiameter = new int[1]; // to

hold the max diameter during recursion heightAndDiameter(root,

maxDiameter); return maxDiameter[0];

private int heightAndDiameter(TreeNode node, int[] maxDiameter) {

if (node == null) return 0;

int leftHeight = heightAndDiameter(node.left, maxDiameter);

int rightHeight = heightAndDiameter(node.right, maxDiameter);

maxDiameter[0] = Math.max(maxDiameter[0], leftHeight + rightHeight);

return Math.max(leftHeight, rightHeight) + 1;

}
}

28. Check if a Binary Tree is Balanced:

public class BinaryTree

{ class TreeNode {

int val;

TreeNode left, right;

TreeNode(int x) { val = x; }

public boolean isBalanced(TreeNode root)

{ return checkHeight(root) != -1;

private int checkHeight(TreeNode node) {

if (node == null) return 0;

int leftHeight = checkHeight(node.left);

if (leftHeight == -1) return -1;

int rightHeight = checkHeight(node.right);

if (rightHeight == -1) return -1;

if (Math.abs(leftHeight - rightHeight) > 1) return -1;

return Math.max(leftHeight, rightHeight) + 1;

29. Lowest Common Ancestor:

public class BinaryTree

{ class TreeNode {

int val;
TreeNode left, right;

TreeNode(int x) { val = x; }

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

if (root == null || root == p || root == q) return root;

TreeNode left = lowestCommonAncestor(root.left, p, q);

TreeNode right = lowestCommonAncestor(root.right, p, q);

if (left == null) return right;

if (right == null) return left;

return root;

30. Implement Graph Using Adjacency List:

import java.util.*;

public class Graph { private Map<Integer,

List<Integer>> adjList;

public Graph() { adjList =

new HashMap<>();

public void addVertex(int vertex)

{ adjList.putIfAbsent(vertex, new ArrayList<>());

}
public void addEdge(int u, int v)

{ adjList.putIfAbsent(u, new ArrayList<>());

adjList.putIfAbsent(v, new ArrayList<>());

adjList.get(u).add(v); adjList.get(v).add(u); //

For undirected graph

public List<Integer> getAdjVertices(int vertex)

{ return adjList.getOrDefault(vertex, new

ArrayList<>());

31. Breadth-First Search (BFS):

import java.util.*;

public class Graph { private Map<Integer,

List<Integer>> adjList;

public Graph() { adjList =

new HashMap<>();

public void bfs(int start) {

Set<Integer> visited = new HashSet<>();

Queue<Integer> queue = new LinkedList<>();

queue.add(start);

visited.add(start);

while (!queue.isEmpty()) {

int vertex = queue.poll();


System.out.print(vertex + " ");

for (int neighbor : adjList.getOrDefault(vertex, new ArrayList<>())) {

if (!visited.contains(neighbor)) { queue.add(neighbor);

visited.add(neighbor);

32. Depth-First Search (DFS):

java

Copy code import

java.util.*;

public class Graph { private Map<Integer,

List<Integer>> adjList;

public Graph() { adjList =

new HashMap<>();

public void dfs(int start) {

Set<Integer> visited = new HashSet<>();

dfsUtil(start, visited);

private void dfsUtil(int vertex, Set<Integer> visited)

{ visited.add(vertex);

System.out.print(vertex + " ");


for (int neighbor : adjList.getOrDefault(vertex, new ArrayList<>())) {

if (!visited.contains(neighbor)) { dfsUtil(neighbor, visited);

33. Detect Cycle in an Undirected Graph:

import java.util.*;

public class Graph {

private Map<Integer, List<Integer>> adjList;

public Graph() { adjList =

new HashMap<>();

public boolean hasCycle() {

Set<Integer> visited = new HashSet<>();

for (int vertex : adjList.keySet())

{ if (!visited.contains(vertex)) {

if (hasCycleUtil(vertex, visited, -1)) {

return true;

return false;

}
private boolean hasCycleUtil(int vertex, Set<Integer> visited, int parent)

{ visited.add(vertex);

for (int neighbor : adjList.getOrDefault(vertex, new ArrayList<>())) {

if (!visited.contains(neighbor)) { if (hasCycleUtil(neighbor,

visited, vertex)) { return true;

} else if (neighbor != parent) {

return true;

return false;

34. Connected Components in an Undirected Graph:

import java.util.*;

public class Graph { private Map<Integer,

List<Integer>> adjList;

public Graph() { adjList =

new HashMap<>();

public int countConnectedComponents() {

Set<Integer> visited = new HashSet<>(); int

count = 0;
for (int vertex : adjList.keySet()) {

if (!visited.contains(vertex))

{ dfsUtil(vertex, visited);

count++;

return count;

private void dfsUtil(int vertex, Set<Integer> visited)

{ visited.add(vertex); for (int neighbor :

adjList.getOrDefault(vertex, new ArrayList<>())) { if (!

visited.contains(neighbor)) { dfsUtil(neighbor, visited);

35. Find MST Using Kruskal’s Algorithm:

import java.util.*;

public class KruskalMST {

public class Edge

{ int u, v, weight;

Edge(int u, int v, int weight) {

this.u = u; this.v = v;

this.weight = weight;

public int kruskal(List<Edge> edges, int vertices) {


Collections.sort(edges, Comparator.comparingInt(e -> e.weight));

int[] parent = new int[vertices]; int[] rank = new int[vertices];

Arrays.fill(parent, -1);

int mstWeight = 0; for (Edge

edge : edges) { int rootU =

find(parent, edge.u); int rootV =

find(parent, edge.v); if (rootU !=

rootV) { mstWeight +=

edge.weight; union(parent, rank,

rootU, rootV);

return mstWeight;

private int find(int[] parent, int u) { if

(parent[u] == -1) return u; return

parent[u] = find(parent, parent[u]);

private void union(int[] parent, int[] rank, int u, int v) {

int rootU = find(parent, u); int rootV = find(parent,

v); if (rank[rootU] > rank[rootV])

{ parent[rootV] = rootU;

} else if (rank[rootU] < rank[rootV])

{ parent[rootU] = rootV;

} else

{ parent[rootV] =

rootU; rank[rootU]++;

}
}

36. Find MST Using Prim’s Algorithm:

import java.util.*;

public class PrimMST { public int

prim(List<List<Edge>> adjList, int vertices) { int[]

key = new int[vertices]; boolean[] mstSet = new

boolean[vertices]; Arrays.fill(key,

Integer.MAX_VALUE); key[0] = 0;

PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.weight));

pq.add(new Edge(0, 0, 0)); int mstWeight = 0; while (!pq.isEmpty()) { Edge edge =

pq.poll(); int u = edge.u;

if (mstSet[u]) continue;

mstSet[u] = true; mstWeight

+= edge.weight;

for (Edge neighbor : adjList.get(u))

{ int v = neighbor.v; if (!mstSet[v]

&& neighbor.weight < key[v]) { key[v] =

neighbor.weight; pq.add(new Edge(u, v,

key[v]));

return mstWeight;

}
public class Edge { int u, v,

weight; Edge(int u, int v, int

weight) { this.u = u;

this.v = v; this.weight =

weight;

37. Fibonacci Sequence (Dynamic Programming):

public class Fibonacci {

public int fib(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:

public class ClimbingStairs

{ public int climbStairs(int n) {

if (n <= 2) return n;

int[] dp = new int[n + 1];

dp[1] = 1; dp[2] = 2;
for (int i = 3; i <= n; i++) {

dp[i] = dp[i - 1] + dp[i - 2];

return dp[n];

39. Min Cost Climbing Stairs:

public class MinCostClimbingStairs { public

int minCostClimbingStairs(int[] cost) { int

n = cost.length; int[] dp = new int[n + 1];

dp[0] = dp[1] = 0;

for (int i = 2; i <= n; i++) { dp[i] = Math.min(dp[i - 1] +

cost[i - 1], dp[i - 2] + cost[i - 2]);

return dp[n];

40. House Robber:

public class HouseRobber { public int

rob(int[] nums) { if (nums.length ==

0) return 0; if (nums.length == 1)

return nums[0];

int prev2 = 0, prev1 = 0;


for (int num : nums) { int temp =

prev1; prev1 = Math.max(prev1, prev2

+ num); prev2 = temp;

return prev1;

41. Maximum Subarray Sum (Kadane’s Algorithm):

java

Copy code public class MaxSubarraySum { public int

maxSubArray(int[] nums) { int maxSoFar = nums[0],

maxEndingHere = nums[0];

for (int i = 1; i < nums.length; i++) { maxEndingHere =

Math.max(nums[i], maxEndingHere + nums[i]); maxSoFar =

Math.max(maxSoFar, maxEndingHere);

return maxSoFar;

42. Activity Selection: java

Copy code import

java.util.*;

public class ActivitySelection { public int

maxActivities(int[] start, int[] end) { int n =

start.length; int[] selected = new int[n];


// Activity selection: Greedy approach based on finish times

List<Integer> activities = new ArrayList<>(); for (int i = 0; i <

n; i++) activities.add(i);

// Sort by end times

activities.sort((a, b) -> end[a] - end[b]) int

count = 1; int lastSelected =

activities.get(0); for (int i = 1; i < n; i+

+) { if (start[activities.get(i)] >=

end[lastSelected]) { lastSelected

= activities.get(i); count++;

return count;

43. Fractional Knapsack Problem:

public class FractionalKnapsack {

class Item { int value, weight;

Item(int v, int w) { value =

v; weight = w;

public double knapSack(int W, int[] values, int[] weights, int n)

{ Item[] items = new Item[n];

for (int i = 0; i < n; i++) { items[i] =

new Item(values[i], weights[i]);

Arrays.sort(items, (a, b) -> Double.compare((double) b.value / b.weight, (double) a.value /


a.weight)); double totalValue = 0.0; for (Item item : items) { if (W == 0) break;
if (item.weight <= W) {
W -= item.weight;

totalValue += item.value;

} else {

totalValue += item.value * ((double) W / item.weight);

break;

return totalValue;

44. Huffman Coding: import

java.util.*; public class

HuffmanCoding { class

Node { char data;

int freq;

Node left, right;

Node(char data, int freq) {

this.data = data; this.freq

= freq;

public void buildHuffmanTree(String text) {

Map<Character, Integer> frequencyMap = new HashMap<>();

for (char c : text.toCharArray()) { frequencyMap.put(c,

frequencyMap.getOrDefault(c, 0) + 1);

PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a.freq));

for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) { pq.offer(new

Node(entry.getKey(), entry.getValue()));

}
while (pq.size() > 1) {

Node left = pq.poll();

Node right = pq.poll();

Node merged = new Node('\0', left.freq + right.freq);

merged.left = left; merged.right = right;

pq.offer(merged);

Node root = pq.poll();

printCodes(root, "");

private void printCodes(Node root, String code) {

if (root == null) return; if (root.data != '\0') {

System.out.println(root.data + ": " + code);

printCodes(root.left, code + "0");

printCodes(root.right, code + "1");

45. Job Sequencing Problem:

import java.util.*; public

class JobSequencing {

class Job { int id, deadline,

profit; Job(int id, int deadline, int

profit) { this.id = id;

this.deadline = deadline;

this.profit = profit;

public int maxProfit(Job[] jobs, int n)

{ Arrays.sort(jobs, (a, b) -> b.profit - a.profit);


boolean[] slots = new boolean[n]; Arrays.fill(slots,

false); int profit = 0; for (Job job : jobs) { for

(int j = Math.min(n, job.deadline) - 1; j >= 0; j--) {

if (!slots[j]) {

slots[j] = true;

profit += job.profit;

break;

return profit;

46. Minimum Number of Coins:

import java.util.*;

public class CoinChange { public int

minCoins(int[] coins, int amount) { int[] dp =

new int[amount + 1]; Arrays.fill(dp,

Integer.MAX_VALUE); dp[0] = 0; for (int

coin : coins) { for (int i = coin; i <= amount;

i++) { if (dp[i - coin] !=

Integer.MAX_VALUE) { dp[i] =

Math.min(dp[i], dp[i - coin] + 1);

return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];

}
47. N-Queens Problem: public class

NQueens { public boolean

solveNQueens(int n) { int[] board =

new int[n]; return solve(board, 0,

n);

private boolean solve(int[] board, int row, int n) {

if (row == n) return true; for (int col = 0; col <

n; col++) { if (isSafe(board, row, col, n)) {

board[row] = col; if (solve(board, row + 1,

n)) return true; board[row] = -1;

return false;

private boolean isSafe(int[] board, int row, int col, int n) { for (int i =

0; i < row; i++) { if (board[i] == col || Math.abs(board[i] - col) ==

Math.abs(i - row)) {

return false;

return true;

public void printSolution(int[] board, int n) {

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();
}

48. Permutations: import java.util.*; public class

Permutations { public List<List<Integer>>

permute(int[] nums) { List<List<Integer>>

result = new ArrayList<>();

permuteHelper(nums, 0, result);

return result;

private void permuteHelper(int[] nums, int index, List<List<Integer>> result) {

if (index == nums.length) {

List<Integer> perm = new ArrayList<>();

for (int num : nums)

{ perm.add(num);

result.add(perm);

return;

for (int i = index; i < nums.length; i++)

{ swap(nums, index, i);

permuteHelper(nums, index + 1, result);

swap(nums, index, i);

private void swap(int[] nums, int i, int j) {

int temp = nums[i]; nums[i] = nums[j];

nums[j] = temp;

}
49. Subsets: import java.util.*; public class

Subsets { public List<List<Integer>>

subsets(int[] nums) { List<List<Integer>>

result = new ArrayList<>(); result.add(new

ArrayList<>()); for (int num : nums)

{ int size = result.size(); for (int i = 0; i

< size; i++) {

List<Integer> subset = new ArrayList<>(result.get(i));

subset.add(num); result.add(subset);

return result;

You might also like