Abhijeet ADSA File
Abhijeet ADSA File
Lab File
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)
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)
public Stack() {
this.top = null;
this.size = 0;
}
return size;
}
// Example Usage
public static void main(String[] args)
{ Stack stack = new Stack();
stack.push(1); stack.push(2);
stack.push(3);
// 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);
Time complexity=0(1)
Space complexity =0(n)
public Queue() {
this.front = null;
this.rear = null; this.size
= 0;
}
// Example Usage
public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue(1);
queue.enqueue(2); queue.enqueue(3);
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){
SPACECOMPLEXITY-O(n)
Program 22. Write a program to implement an Inorder Traversal:
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)
root) {
if(root==null){
return;
}
answer.add(root.val);
preOrder(root.left, answer);
preOrder(root.right, answer);
}
}
Output –
TIMECOMPLEXITY-O(N)
SPACECOMPLEXITY-O(H)
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
TIMECOMPLEXITY-O(N) SPACECOMPLEXITY-O(H)
Output –
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)
TIMECOMPLEXITY-O(N)
Program Write a program to implement a
Write a function to
SPACECOMPLEXITY-O(H)
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()) {
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 4);
TIMECOMPLEXITY- O(V+E)
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<>();
}
}
if (!visited[neighbor]) {
if (dfs(neighbor, visited, v)) {
return true;
}
}
boolean isCyclic() {
boolean[] visited = new boolean[vertices];
}
}
graph[0].add(1);
graph[1].add(0);
graph[2].add(3);
graph[3].add(2);
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.
if (x != y) {
mst.add(edge);
union(subsets, x, y);
e++; }
if (e == V - 1) break;
}
kruskalMST(V, edges);
}}
Complexity
Write a function to find the Minimum Spanning a graph using Prim’s algorithm.
import java.util.*;
class Graph {
while (!pq.isEmpty()) {
if (inMST[u]) continue;
inMST[u] = true;
totalWeight += edge.weight;
if (edge.weight != 0) {
mstEdges.add(edge);
}
primMST(V, adj);
}}
Complexity
Complexity
Space Complexity:O(n)
Output
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.
return b;
}
Complexity
Complexity
int prev2 = 0;
int prev1 = nums[0];
return prev1;
}
Complexity
Write a function to find the contiguous subarray with the maximum sum.
return maxSum;
}
Complexity
• Time Complexity: O(n)
• Space Complexity: O(1)
import java.util.Arrays;
return count;
}
}}
Complexity
maxValue += item.value;
capacity -= item.weight;
} else {
return maxValue;
}
}}
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.
HuffmanCoding {
pq.add(internalNode);
}
return pq.poll();
}
printHuffmanCodes(root, "");
}}
Complexity
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;
return totalProfit;
}
}}
Complexity
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 {
Complexity
• Time Complexity: O(n \times m)
• Space Complexity: O(n) Output:
class NQueens {
private static boolean isSafe(int[] board, int row, int col, int n) {
for (int i = 0; i < row; i++) {
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 {
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 {
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);
}
}
Complexity
• Time Complexity: O(2^n)
• Space Complexity: O(n)
Output:
[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]