0% found this document useful (0 votes)
3 views77 pages

Abhijeet ADSA File

The document contains a lab file for an Advanced Data Structures and Algorithms course, authored by Abhijeet Raj. It includes various programming tasks related to data structures such as arrays, linked lists, stacks, queues, and binary trees, detailing their respective time and space complexities. Each task is accompanied by a program implementation and example usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views77 pages

Abhijeet ADSA File

The document contains a lab file for an Advanced Data Structures and Algorithms course, authored by Abhijeet Raj. It includes various programming tasks related to data structures such as arrays, linked lists, stacks, queues, and binary trees, detailing their respective time and space complexities. Each task is accompanied by a program implementation and example usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Department of Computer Science & Engineering

Subject: Advanced Data Structures And Algorithms

Lab File

Name: Abhijeet Raj


Admission No: 22SCSE1010547
Section :12
Batch : P2
Submitted To: Mr. Kumar Vikas

1. Write a function to find the maximum and minimum elements


in an array.
Program:

Time complexity: O(n)


Space complexity: O(1)

2.Write a function to reverse an array in place.


Program:
Time complexity: O(n)
Space complexity: O(1)
3.Write a function to find the Kth smallest or largest element in an
array.
Program:
Timpe complexity:average case :0(n)//worst case:0(n2)
Space complexity:0(1)

4.Given an array containing only 0s, 1s, and 2s, sort the array in
linear time.
Program:
Time complexity:0(n)
Space complexity:0(1)
5.Write a function to move all zeroes in an array to the end while
maintaining the relative order of other elements.
Program:
Time complexity: O(n)
Space complexity: O(1)

6.Write a function to detect if a cycle exists in a linked list.


Program:

Time complexity: O(n)


Space complexity: O(1)

7.Write a function to reverse a singly linked list.


Program:

Time complexity: O(n)


Space complexity: O(1)

8.Write a function to find the middle element of a linked list.


Program:

Time complexity: O(n)


Space complexity: O(1)

9.Write a function to merge two sorted linked lists into one


sorted linked list.
Program:

Time complexity: O(m+n)


Space complexity: O(m+n)

10.Write a function to merge two sorted linked lists into one sorted
linked list.
Program:
Time complexity: O(m+n)
Space complexity: O(m+n)

11.Write a function to remove the Nth node from the start/end of a


linked list.
Program:
Time complexity: O(n)
Space complexity: O(1)

12.Write a function to implement a stack using an array or list with


basic operations: push, pop, peek, and isEmpty.
Program:
Time complexity:0(1)
Space complexity:0(n)

13.Write a function to implement a stack using a linked list with


basic operations: push, pop, peek, and isEmpty.
Program:
class Stack {
private Node top; // Pointer to the top node
private int size; // To keep track of the stack size

public Stack() {
this.top = null;
this.size = 0;
}

// Push an item onto the stack


public void push(int item) {
Node newNode = new Node(item);
newNode.next = top; // Point new node to the previous top
top = newNode; // Update the top to the new node
size++;
}

// Pop an item from the stack


public int pop() { if
(isEmpty()) {
throw new IllegalStateException("pop from empty stack");
}
int poppedItem = top.data; // Get the data from the top
node
top = top.next; // Move the top pointer to the next
node
size--;
return poppedItem;
}

// Peek at the top item of the stack


public int peek() { if (isEmpty()) {
throw new IllegalStateException("peek from empty
stack");
}
return top.data;
}

// Check if the stack is empty


public boolean isEmpty() {
return top == null;
}

// Get the size of the stack


public int size() {

return size;
}

// Example Usage
public static void main(String[] args)
{ Stack stack = new Stack();
stack.push(1); stack.push(2);
stack.push(3);

System.out.println("Top item: " + stack.peek()); // Output: 3


System.out.println("Popped item: " + stack.pop()); //
Output: 3
System.out.println("Is stack empty? " + stack.isEmpty()); //
Output: false
System.out.println("Popped item: " + stack.pop()); //
Output: 2
System.out.println("Popped item: " + stack.pop()); //
Output: 1
System.out.println("Is stack empty? " + stack.isEmpty()); //
Output: true
}
}
14.Write a function to check if a string containing parentheses is
balanced.
Program: import java.util.Stack;

public class ParenthesesChecker { public


static boolean isBalanced(String str) {
Stack<Character> stack = new Stack<>();

for (char ch : str.toCharArray()) {


// If the character is an opening parenthesis, push it onto the
stack
if (ch == '(') {
stack.push(ch);
}
// If it's a closing parenthesis, check for balance
else if (ch == ')') {
// If the stack is empty, it means there's no matching
opening parenthesis
if (stack.isEmpty()) {
return false;
}
stack.pop(); // Pop the matching opening parenthesis
}
}

// If the stack is empty, all parentheses are balanced


return stack.isEmpty();
}

public static void main(String[] args) {


String testString1 = "(())"; // Balanced
String testString2 = "(()))"; // Not Balanced
String testString3 = "(()())"; // Balanced

System.out.println("Is balanced? " + isBalanced(testString1)); //


Output: true
System.out.println("Is balanced? " + isBalanced(testString2)); //
Output: false
System.out.println("Is balanced? " + isBalanced(testString3)); //
Output: true
}
}

Time Complexity: O(n)


Space Complexity: O(n)
15.
Program:
Time complexity:0(n)
Space complexity:0(n)

16.Write a function to implement a queue using an array or list with


basic operations: enqueue, dequeue, front, and isEmpty.
Program: class Queue {
private int[] arr; // Array to store queue elements
private int front; // Index of the front element private
int rear; // Index of the rear element
private int size; // Current number of elements in the queue
private int capacity; // Maximum capacity of the queue

// Constructor to initialize the queue


public Queue(int capacity) {
this.capacity = capacity; arr = new
int[capacity]; front = 0; rear = -
1; size = 0;
}

// Enqueue an item to the rear of the queue


public void enqueue(int item) { if (size ==
capacity) {
throw new IllegalStateException("Queue is full");
}
rear = (rear + 1) % capacity; // Circular increment
arr[rear] = item; // Add item to the rear size++;

// Dequeue an item from the front of the queue


public int dequeue() { if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int dequeuedItem = arr[front]; // Get the front item
front = (front + 1) % capacity; // Circular increment size--;
return dequeuedItem;
}

// Get the front item of the queue without removing it


public int front() { if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return arr[front];
}

// Check if the queue is empty


public boolean isEmpty() {
return size == 0;

// Get the current size of the queue


public int size() { return size;
}

// Example Usage
public static void main(String[] args) {
Queue queue = new Queue(5); // Create a queue with capacity
5
queue.enqueue(1);
queue.enqueue(2); queue.enqueue(3);

System.out.println("Front item: " + queue.front()); // Output: 1


System.out.println("Dequeued item: " + queue.dequeue()); //
Output: 1
System.out.println("Is queue empty? " + queue.isEmpty()); //
Output: false
System.out.println("Dequeued item: " + queue.dequeue()); //
Output: 2
System.out.println("Dequeued item: " + queue.dequeue()); //
Output: 3
System.out.println("Is queue empty? " + queue.isEmpty()); //
Output: true
}
}

Output= Front item: 1


Dequeued item: 1
Is queue empty? false
Dequeued item: 2
Dequeued item: 3
Is queue empty? True

Time complexity=0(1)
Space complexity =0(n)

17.Write a function to implement a queue using a linked list with


basic operations: enqueue, dequeue, front, and isEmpty. Program:
class Queue {
private Node front; // Pointer to the front of the queue
private Node rear; // Pointer to the rear of the queue private
int size; // Size of the queue

public Queue() {
this.front = null;
this.rear = null; this.size
= 0;
}

// Enqueue an item to the rear of the queue


public void enqueue(int item) {
Node newNode = new Node(item);
if (rear == null) { //
Queue is empty front =
rear = newNode;
} else {
// Add new node at the end of the queue
rear.next = newNode; rear = newNode;
}
size++;
}
// Dequeue an item from the front of the queue
public int dequeue() { if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int dequeuedItem = front.data; // Get the front item
front = front.next; // Move the front pointer to the next node
if (front == null) {
rear = null; // If the queue becomes empty, set rear to null
}
size--;
return
dequeuedIt
em;

// Get the front item of the queue without removing it


public int front() { if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return front.data;
}
// Check if the queue is empty
public boolean isEmpty() {
return front == null;
}

// Get the current size of the queue


public int size() { return size;
}

// Example Usage
public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue(1);
queue.enqueue(2); queue.enqueue(3);

System.out.println("Front item: " + queue.front()); // Output: 1


System.out.println("Dequeued item: " + queue.dequeue()); //
Output: 1
System.out.println("Is queue empty? " + queue.isEmpty()); //
Output: false
System.out.println("Dequeued item: " + queue.dequeue()); //
Output: 2
System.out.println("Dequeued item: " + queue.dequeue()); //
Output: 3
System.out.println("Is queue empty? " + queue.isEmpty()); //
Output: true
}
}
Time complexity = 0(1)
Space complexity=0(n)

18.Write a function to implement a circular queue with basic


operations: enqueue, dequeue, front, rear, and isEmpty.
Program:
Time complexity:
Space complexity:
Time complexity:
Space complexity:
19.Write a function to generate binary numbers from 1 to N using a
queue.
Program:

Time complexity: 0(N)


Space complexity:0(N)
Program 21. Write a program to implement a Binary Tree

Write a class to implement a basic binary tree with insert,delete, and

traversal operations.

class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if(Height(root) == -1) return false;
return true;
}
private int Height (TreeNode root){

if(root == null) return 0; int


leftHeight = Height(root.left); int
rightHeight = Height(root.right);

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


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

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


}
}
Output –
TIMECOMPLEXITY-O(n)

SPACECOMPLEXITY-O(n)
Program 22. Write a program to implement an Inorder Traversal:

Write a function to perform inorder traversal of a binary tree.

class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> answer = new ArrayList<>();
inOrder(root, answer); return answer;
}
private void inOrder(TreeNode root, List<Integer> answer){
if(root==null){
return;
}
inOrder(root.left, answer);
answer.add(root.val);
inOrder(root.right, answer);
}
}public class Main { public static void
main(String[] args) { TreeNode root =
new TreeNode(1); root.right = new
TreeNode(2); root.right.left = new
TreeNode(3);
Solution solution = new Solution();
List<Integer> result = solution.inorderTraversal(root);
System.out.println("Inorder Traversal of the Binary Tree: " + result);
}
}
Output –

TIMECOMPLEXITY-O(N)
SPACECOMPLEXITY-O(H)

Program 23. Write a program to implement a Preorder Traversal:

Write a function to perform preorder traversal of a binary tree.

class Solution { public List<Integer> preorderTraversal(TreeNode

root) {

ArrayList<Integer> answer = new ArrayList<>();


preOrder(root, answer); return answer;
}
private void preOrder(TreeNode root, List<Integer> answer){

if(root==null){
return;
}
answer.add(root.val);
preOrder(root.left, answer);
preOrder(root.right, answer);
}
}
Output –

TIMECOMPLEXITY-O(N)
SPACECOMPLEXITY-O(H)

Program 24. Write a program to implement a Postorder Traversal:

Write a function to perform postorder traversal of a binary tree.

class Solution {
public List<Integer> postorderTraversal(TreeNode root) {

ArrayList<Integer> answer = new


ArrayList<>(); preOrder(root, answer); return
answer;
}
private void preOrder(TreeNode root, List<Integer> answer){
if(root==null){
return;
}
preOrder(root.left, answer);
preOrder(root.right, answer);
answer.add(root.val);
}
}
Output –

TIMECOMPLEXITY-O(N) SPACECOMPLEXITY-O(H)

Program 25. Write a program to implement a Level Order Traversal:

Write a function to perform level order traversal of a binary tree.


class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root==null) return ans;
Queue<TreeNode> q = new LinkedList<>();
q.add(root); while(q.size()>0){
List<Integer> arr = new ArrayList<>();
int n = q.size(); for(int i=0; i<n; i++){
TreeNode a = q.remove();
arr.add(a.val); if(a.left!=null)
q.add(a.left); if(a.right!=null)
q.add(a.right);
}
ans.add(arr);
}
return ans;
}
}

Output –

Program 26. Write a program to implement a Height of a


BinaryTree:
Write a function to find the height of a binary tree.

class Node {
int data; Node
left, right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
class Tree{
static int height(Node root) {
if (root == null)
return -1;
int lHeight = height(root.left); int
rHeight = height(root.right); return
Math.max(lHeight, rHeight) + 1;
}
public static void main(String[] args) {
Node root = new Node(1); root.left
= new Node(2); root.right = new
Node(3); root.left.left = new
Node(4); root.left.right = new
Node(5);
System.out.println(height(root));
}
}

Output –

TIMECOMPLEXITY-O(N)

SPACECOMPLEXITY-O(H)
Program Write a program to implement a
Write a function to
26. Diameter of a Binary Tree: find the diameter of a binary
tree.

class Solution {
int length; public int
diameterOfBinaryTree(TreeNode root) {
length = 0;
calLength(root);
return length;
}
private int calLength(TreeNode node){
if(node==null){
return 0;
}
int left = calLength(node.left); int
right = calLength(node.right); length
= Math.max(length, left+right);
return 1+Math.max(left, right);
}
}
Output –

TIMECOMPLEXITY-O(N)
Program Write a program to implement a
Write a function to
SPACECOMPLEXITY-O(H)

28. Check if a Binary Tree is Balanced:


check if a binary tree is height balanced
.
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if(Height(root) == -1) return false;
return true;
}
private int Height (TreeNode root){ if(root == null)
return 0; int leftHeight = Height(root.left); int
rightHeight = Height(root.right); if(leftHeight == -1
|| rightHeight == -1) return -1;
if(Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight , rightHeight) + 1;
}
}
Output –

TIMECOMPLEXITY-O(N)
Program Write a program to implement a
Write a function to
SPACECOMPLEXITY-O(H)

29. Lowest Common Ancestor: find the lowest common ancestor


of two nodes in a binary tree.
class Solution {
private static TreeNode out; private static boolean helper(TreeNode
root, TreeNode p, TreeNode q) {
if (root == null)
return false;
boolean a = helper(root.left, p, q);
boolean b = helper(root.right, p, q); if
(root.val == p.val || root.val == q.val) {
if (a || b)
out = root;
return true;
}
if (a && b)
out = root;
return a || b;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
helper(root, p, q);
return out;
}
}
Program Write a program to implement a
Write a function to
Output –
TIMECOMPLEXITY-O(N)

SPACECOMPLEXITY-O(H)

Program 30. Write a program to implement a Implement Graph Using Adjacency List:
Write a class to implement a basic graph usingan adjacency list with methods to add vertices
and edges.

import java.util.*;
class Graph {
static void addEdge(ArrayList<ArrayList<Integer>> am, int s, int d) {
am.get(s).add(d);
am.get(d).add(s);
}
public static void main(String[] args) {
int V = 5;
ArrayList<ArrayList<Integer>> am = new ArrayList<ArrayList<Integer>>(V);
for (int i = 0; i < V; i++)
am.add(new ArrayList<Integer>());
addEdge(am, 0, 1); addEdge(am, 0,
2); addEdge(am, 0, 3);
addEdge(am, 1, 2); printGraph(am);
}
static void printGraph(ArrayList<ArrayList<Integer>> am) {
for (int i = 0; i < am.size(); i++) {
System.out.println("\nVertex " + i + ":");
for (int j = 0; j < am.get(i).size(); j++) {
System.out.print(" -> " + am.get(i).get(j));
}
System.out.println();
}
}
}
Program 31. Write a program to a Implement Breadth-First Search (BFS): Write
a function to perform BFS on a graph from a givenstart vertex
import java.util.*;
class GfG {
static void bfs(List<List<Integer>> adj, int s) {
Queue<Integer> q = new LinkedList<>();
boolean[] visited = new boolean[adj.size()];
visited[s] = true; q.add(s); while
(!q.isEmpty()) {

int curr = q.poll();


System.out.print(curr + " ");
for (int x : adj.get(curr)) {
if (!visited[x]) {
visited[x] = true;
q.add(x);
}
}
}
}

static void addEdge(List<List<Integer>> adj, int u, int v) {


adj.get(u).add(v); adj.get(v).add(u); //
Undirected graph
}
public static void main(String[] args) {
int V = 5;

List<List<Integer>> adj = new ArrayList<>(V);


for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}

addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 4);

System.out.println("BFS starting from 0:");


bfs(adj, 0);
}
}

TIMECOMPLEXITY- O(V+E)

Program 32. Write a program to a Implement Depth-First Search (DFS):


Write a function to perform DFS on a graph from a given start vertex.
import java.util.ArrayList; import java.util.List; class GfG { static void
DFSRec(List<List<Integer> > adj, boolean[] visited, int s){
visited[s] = true;
System.out.print(s + " ");
for (int i : adj.get(s)) {
if (!visited[i]) {
DFSRec(adj, visited, i);
}
}
}
static void DFS(List<List<Integer> > adj, int s) {
boolean[] visited = new boolean[adj.size()];

DFSRec(adj, visited, s);


}
static void addEdge(List<List<Integer> > adj, int
s, int t){
adj.get(s).add(t);
adj.get(t).add(s);
}
public static void main(String[] args)
{
int V = 5; // Number of vertices in the graph
List<List<Integer> > adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
int[][] edges = {
{ 1, 2 }, { 1, 0 }, { 2, 0 }, { 2, 3 }, { 2, 4 }
};
for (int[] e : edges) {
addEdge(adj, e[0], e[1]);
}
int source = 1;
System.out.println("DFS from source: " + source);
DFS(adj, source);
}
}

Time complexity: O(V + E)


Program 33. Write a program to a Detect Cycle in an Undirected Graph: Write
a function to detect if there is a cycle in an undirected graph.

import java.util.*;
class Graph {
private int vertices;
private LinkedList<Integer>[] adjList;
Graph(int v) { vertices = v;
adjList = new LinkedList[v];
for (int i = 0; i < v; i++) {
adjList[i] = new LinkedList<>();
}
}

void addEdge(int v, int w) {


adjList[v].add(w);
adjList[w].add(v);
}
private boolean dfs(int v, boolean[] visited, int parent) {
visited[v] = true;
// Recur for all the vertices adjacent to this vertex
for (Integer neighbor : adjList[v]) {

if (!visited[neighbor]) {
if (dfs(neighbor, visited, v)) {
return true;
}
}

else if (neighbor != parent) {


return true;
}
}
return false;
}

boolean isCyclic() {
boolean[] visited = new boolean[vertices];

for (int i = 0; i < vertices; i++) {


if (!visited[i]) {
if (dfs(i, visited, -1)) {
return true; }
}
}
return false;
}

}
}

Time complexity: O(V + E)


AIM:-
AIM:- Connected Components in an Undirected Graph

Write a function to find the number of connected components in an undirected graph.

import java.util.*; public


class Graph {
public void dfs(List<Integer>[] graph, boolean[] visited, int node) {
visited[node] = true; for (int neighbor : graph[node]) { if
(!visited[neighbor]) {
dfs(graph, visited, neighbor);
}
}
}

public int countConnectedComponents(List<Integer>[] graph, int n) {


boolean[] visited = new boolean[n]; int components = 0;

for (int node = 0; node < n; node++) {


if (!visited[node]) {
dfs(graph, visited, node);
components++;
}
}
return components;
}

public static void main(String[] args) {


Graph g = new Graph(); int n = 5;
// Number of nodes
List<Integer>[] graph = new ArrayList[n];

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


graph[i] = new ArrayList<>();
}

graph[0].add(1);
graph[1].add(0);
graph[2].add(3);
graph[3].add(2);

System.out.println("Number of connected components: " +


g.countConnectedComponents(graph, n));
}}

Complexity
Time Complexity: O(V + E)
Space Complexity: O(V)
Output
Number of connected components: 3
Find MST Using Kruskal’s Algorithm

Write a function to find the Minimum Tree of a graph using Kruskal’s algorithm.

import java.util.*; class


Graph { static class
Edge { int src, dest,
weight;
public Edge(int src, int dest, int weight) {
this.src = src; this.dest = dest;
this.weight = weight;
}
}
static class Subset {
int parent, rank;
}
static int find(Subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}

static void union(Subset subsets[], int x, int y) {


int xroot = find(subsets, x); int yroot =
find(subsets, y);

if (subsets[xroot].rank < subsets[yroot].rank)


subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot; else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
public static void kruskalMST(int V, List<Edge> edges) {
Collections.sort(edges, Comparator.comparingInt(e -> e.Subset subsets[] =
new Subset[V];
for (int i = 0; i < V; i++) {
subsets[i] = new Subset();
subsets[i].parent = i;
subsets[i].rank = 0;
}

List<Edge> mst = new ArrayList<>();


int e = 0;
AIM:-
for (Edge edge : edges) {
int x = find(subsets, edge.src);
int y = find(subsets, edge.dest);

if (x != y) {
mst.add(edge);
union(subsets, x, y);
e++; }

if (e == V - 1) break;
}

System.out.println("Edges in the Minimum Spanning Tree:");


for (Edge edge : mst) {
System.out.println(edge.src + " - " + edge.dest + " : " + edge.weight);
}
}

public static void main(String[] args) {


int V = 4; // Number of vertices
List<Edge> edges = new ArrayList<>();

edges.add(new Edge(0, 1, 10));


edges.add(new Edge(0, 2, 6));
edges.add(new Edge(0, 3, 5));
edges.add(new Edge(1, 3, 15));
edges.add(new Edge(2, 3, 4));

kruskalMST(V, edges);
}}

Complexity

• Time Complexity: O(E \log E)


• Space Complexity: O(E + V) Output

Edges in the Minimum Spanning Tree:


2-3:4
0-3:5
0 - 1 : 10
Find MST Using Prim’s Algorithm

Write a function to find the Minimum Spanning a graph using Prim’s algorithm.

import java.util.*;
class Graph {

static class Edge {


int dest, weight;

public Edge(int dest, int weight) {


this.dest = dest;
this.weight = weight;
}
}

public static void primMST(int V, List<List<Edge>> adj) {

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

boolean[] inMST = new boolean[V];

pq.offer(new Edge(0, 0)); // (vertex, weight)


int totalWeight = 0;

List<Edge> mstEdges = new ArrayList<>();

while (!pq.isEmpty()) {

Edge edge = pq.poll();


int u = edge.dest;

if (inMST[u]) continue;

inMST[u] = true;
totalWeight += edge.weight;

if (edge.weight != 0) {
mstEdges.add(edge);
}

for (Edge e : adj.get(u)) {


if (!inMST[e.dest]) {
pq.offer(new Edge(e.dest, e.weight));
}
}
}
AIM:-
System.out.println("Edges in the Minimum Spanning Tree:");
for (Edge e : mstEdges) {
System.out.println(e.dest + " - " + e.weight);
}
System.out.println("Total weight of the MST: " + totalWeight);
}

public static void main(String[] args) {


int V = 5; // Number of vertices

List<List<Edge>> adj = new ArrayList<>();


for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}

adj.get(0).add(new Edge(1, 2));


adj.get(0).add(new Edge(3, 6));
adj.get(1).add(new Edge(0, 2));
adj.get(1).add(new Edge(2, 3));
adj.get(1).add(new Edge(3, 8));
adj.get(2).add(new Edge(1, 3));
adj.get(2).add(new Edge(3, 7));
adj.get(3).add(new Edge(0, 6));
adj.get(3).add(new Edge(1, 8));
adj.get(3).add(new Edge(2, 7));

primMST(V, adj);
}}

Complexity

• Total Time Complexity: O(E \log V)

• Total Space Complexity: O(V + E) , Output

Edges in the Minimum Spanning Tree:


1-2
2-3
0-2
Total weight of the MST: 12
Fibonacci Sequence

Write a function to compute the nth Fibonacci number using programming.


public class Fibonacci {
public static int fibonacciRecursive(int n) {
if (n <= 1) return n;
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}

public static void main(String[] args) {


int n = 10;
System.out.println("Fibonacci number at position " + n + " is: " + fibonacciRecursive(n));
}}

Complexity

Time Complexity: O(2^n)

Space Complexity:O(n)

Output

Fibonacci number at position 10 is : 55


AIM:-
AIM:- Climbing Stairs

Write a function to determine how many distinct ways there are to climb a staircase with n
steps if you can climb either 1 or 2 steps at a time.

public class Staircase {


public static int climbStairs(int n) {
if (n == 0) return 1; if (n == 1)
return 1; int a = 1, b = 1, c = 0;

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


c = a + b; a = b;
b = c;
}

return b;
}

public static void main(String[] args) {


int n = 5;
System.out.println("Number of distinct ways to climb " + n + " steps: " + climbStairs(n));
}}

Complexity

Time Complexity: O(n) Space


Complexity: O(1) Output:

Number of distinct ways to climb 5 steps: 8


AIM:- Min Cost Climbing Stairs
Write a function to determine the minimum cost to reach the top of a staircase given a list of
costs associated with each step. Code:-

public class MinCostClimbingStairs {


public static int minCostClimbingStairs(int[] cost) {
int n = cost.length; if (n == 0){
return 0;
} if (n
== 1){
return cost[0];
}
int prev2 = cost[0];
int prev1 = cost[1];

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


int current = cost[i] + Math.min(prev1, prev2);
prev2 = prev1;
prev1 = current;
}

return Math.min(prev1, prev2);


}

public static void main(String[] args) {


int[] cost = {10, 15, 20};
System.out.println(minCostClimbingStairs(cost)); // Output: 15
}}

Complexity

• Time Complexity: O(n)


• Space Complexity: O(1)

AIM:- House Robber


Write a function to determine the maximum amount of money you can from a row of houses
without robbing two adjacent houses.
public class HouseRobber {
public static int rob(int[] nums) {
int n = nums.length; if (n ==
0) return 0; if (n == 1) return
nums[0];

int prev2 = 0;
int prev1 = nums[0];

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


int current = Math.max(prev1, prev2 + nums[i]);
prev2 = prev1;
prev1 = current;
}

return prev1;
}

public static void main(String[] args) {


int[] houses = {2, 7, 9, 3, 1};
System.out.println(rob(houses));
}}

Complexity

• Time Complexity: O(n)


• Space Complexity: O(1)

AIM:- Maximum Subarray Sum (Kadane’s Algorithm)

Write a function to find the contiguous subarray with the maximum sum.

public class MaximumSubarray { public


static 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;
}

public static void main(String[] args) {


int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(nums));
}}

Complexity
• Time Complexity: O(n)
• Space Complexity: O(1)

AIM:- Activity Selection


Given a set of activities with start and end times, select the maximum number of activities that do
not overlap.

import java.util.Arrays;

public class ActivitySelection {


static class Activity { int
start, end;

Activity(int start, int end) {


this.start = start;
this.end = end;
}
}

public static int maxActivities(Activity[] activities) {

Arrays.sort(activities, (a, b) -> a.end - b.end);

int count = 1; // At least one activity can always be selected


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

public static void main(String[] args) {


Activity[] activities = {
new Activity(1, 3), new
Activity(2, 5), new
Activity(3, 9), new
Activity(6, 7),
new Activity(8, 9)
};

System.out.println("Maximum number of activities: " + maxActivities(activities));

}}

Complexity

• Time Complexity: O(n \log )


• Space Complexity: O(1)
Fractional Knapsack Problem
Given weights and values of items and the maximum capacity of a knapsack,
determine the maximum value that can be obtained by including fractions of items.

import java.util.Arrays; import


java.util.Comparator;

public class FractionalKnapsack {


static class Item { int weight;
int value;

Item(int weight, int value) {


this.weight = weight;
this.value = value;
}
}

public static double fractionalKnapsack(int capacity, Item[] items) {

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


a.weight));

double maxValue = 0.0;

for (Item item : items) {


if (capacity >= item.weight) {

maxValue += item.value;
capacity -= item.weight;
} else {

maxValue += (double) item.value * capacity / item.weight;


break;
}
}

return maxValue;
}

public static void main(String[] args) {


Item[] items = { new Item(10,
60), new Item(20, 100),
new Item(30, 120)
};
int capacity = 50;

System.out.println("Maximum value in knapsack = " + fractionalKnapsack(capacity, items));

}}

Complexity
AIM:-
• Time Complexity: O(n \log n)
• Space Complexity: O(1)

Output:
Maximum value in knapsack = 240.0
Huffman Coding
Given a set of characters and their frequencies, construct the to encode the characters.

import java.util.PriorityQueue; class

HuffmanCoding {

static class Node {


char ch; int freq;
Node left, right;

public Node(char ch, int freq) {


this.ch = ch; this.freq =
freq; left = right = null;
}
}

static class NodeComparator implements java.util.Comparator<Node> {


public int compare(Node n1, Node n2) { return n1.freq - n2.freq;
}
}

public static Node buildHuffmanTree(char[] chars, int[] freqs) {

PriorityQueue<Node> pq = new PriorityQueue<>(new NodeComparator());

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

pq.add(new Node(chars[i], freqs[i]));


}

while (pq.size() > 1) {


Node left = pq.poll();
Node right = pq.poll();

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


internalNode.left = left; internalNode.right = right;

pq.add(internalNode);
}

return pq.poll();
}

public static void printHuffmanCodes(Node root, String code) {


if (root != null) {
if (root.ch != '\0') {
AIM:-
System.out.println(root.ch + ": " + code);
}
printHuffmanCodes(root.left, code + "0");
printHuffmanCodes(root.right, code + "1");
}
}

public static void main(String[] args) {


char[] chars = {'a', 'b', 'c', 'd', 'e', 'f'}; int[]
freqs = {5, 9, 12, 13, 16, 45};

Node root = buildHuffmanTree(chars, freqs);

printHuffmanCodes(root, "");
}}

Complexity

• Time Complexity: O(n \log n)


• Space Complexity: O(n)

Output:

f: 0 c:
100 d:
101 a:
1100 b:
1101 e:
111
Job Sequencing Problem

Given a set of jobs, each with a deadline and profit, the total profit by scheduling the jobs to be
done before their deadlines. import java.util.Arrays; class JobSequencing { static class Job {
int id, deadline, profit;

Job(int id, int deadline, int profit) {


this.id = id;
this.deadline = deadline;
this.profit = profit;
}
}

static class JobComparator implements java.util.Comparator<Job> {


public int compare(Job j1, Job j2) { return j2.profit - j1.profit;
}
}

public static int jobScheduling(Job[] jobs) {

Arrays.sort(jobs, new JobComparator());


int maxDeadline = 0;
for (Job job : jobs) {
maxDeadline = Math.max(maxDeadline, job.deadline);
}

boolean[] slots = new boolean[maxDeadline + 1];


int totalProfit = 0;

for (Job job : jobs) {

for (int j = job.deadline; j > 0; j--) {


if (!slots[j]) {
slots[j] = true;
totalProfit += job.profit;
break;
}
}
}

return totalProfit;
}

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)
};
System.out.println("Maximum Profit: " + jobScheduling(jobs));

}}

Complexity

• Time Complexity: O(n \log n)


• Space Complexity: O(n)

Output:

Maximum Profit: 60
AIM:-
Minimum Number of Coins
Given different denominations of coins and an amount, find the minimum number of coins needed
to make up that amount. import java.util.Arrays; public class CoinChange {

public static int coinChange(int[] coins, int amount) {

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


Arrays.fill(dp, amount + 1); dp[0]
= 0;

for (int coin : coins) {

for (int i = coin; i <= amount; i++) {


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

return dp[amount] > amount ? -1 : dp[amount];


}

public static void main(String[] args) {


int[] coins = {1, 2, 5}; int amount =
11;
System.out.println("Minimum coins needed: " + coinChange(coins, amount));
}}

Complexity
• Time Complexity: O(n \times m)
• Space Complexity: O(n) Output:

Minimum coins needed: 3


AIM:- N-Queens Problem
Place N queens on an N×N chessboard so that no two queens threaten each other. public

class NQueens {

public static boolean solveNQueens(int n) {

int[] board = new int[n];

return solveNQueensUtil(board, 0, n);


}

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


if (row == n) {
printSolution(board, n);
return true;
}

boolean res = false; for (int


col = 0; col < n; col++) { if
(isSafe(board, row, col, n)) {
board[row] = col;
res = solveNQueensUtil(board, row + 1, n) || res;
}
}
return res;
}

private static 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;
}

private static 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();
}
System.out.println();
}

public static void main(String[] args) {


int n = 4;
if (!solveNQueens(n)) {
System.out.println("Solution does not exist.");
}
}}

Complexity
• Time Complexity: O(n) •
Space Complexity: O(n)

Output:

. Q . .
. . . Q Q
. . .
. . Q .

. . Q .
Q . . .
. . . Q .
Q . .
AIM:- Permutations
Generate all possible permutations of a given list of numbers or characters.

import java.util.ArrayList;
import java.util.List; public
class Permutations {

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


List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums); return
result; }

private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums) {


if (tempList.size() == nums.length) {
result.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < nums.length; i++) {
if (tempList.contains(nums[i])) continue;
tempList.add(nums[i]);
backtrack(result, tempList, nums);
tempList.remove(tempList.size() - 1);
}
}
}

public static void main(String[] args) {


int[] nums = {1, 2, 3};
List<List<Integer>> permutations = permute(nums);

for (List<Integer> perm : permutations) {


System.out.println(perm);
}
}}

Complexity
• Time Complexity: O(n!) •
Space Complexity: O(n!)

Output:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
AIM:- Subsets
Generate all possible subsets of a given set of numbers.

import java.util.ArrayList;
import java.util.List; public
class Subsets {

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


List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums, 0);
return result; }

private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int
start) {
result.add(new ArrayList<>(tempList));
for (int i = start; i < nums.length; i++) {
tempList.add(nums[i]); // Include the current element
backtrack(result, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1);
}
}

public static void main(String[] args) {


int[] nums = {1, 2, 3};
List<List<Integer>> subsets = subsets(nums);

for (List<Integer> subset : subsets) {


System.out.println(subset);
}
}}

Complexity
• Time Complexity: O(2^n)
• Space Complexity: O(n)

Output:

[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

You might also like