V20Syllabus
V20Syllabus
import java.util.Scanner;
import java.util.Stack;
class DynamicQueueUsingStacks
stack1.push(data);
{ if (isEmpty()) {
System.out.println("Queue is empty!");
return -1;
if (stack2.isEmpty()) {
while (!stack1.isEmpty())
{ stack2.push(stack1.pop());
return stack2.pop();
{ if (isEmpty()) {
System.out.println("Queue is empty!");
return;
if (stack2.isEmpty()) {
while (!stack1.isEmpty())
{ stack2.push(stack1.pop());
System.out.println();
do {
choice = sc.nextInt();
switch (choice) {
case 1:
value = sc.nextInt();
queue.enqueue(value);
break;
case 2:
if (removed != -1) {
break;
case 3:
queue.display();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
sc.close();
1b)
import java.util.*;
{ low = mid + 1;
} else {
high = mid;
return arr[low];
int n = sc.nextInt();
arr[i] = sc.nextInt();
2a)
import java.util.*;
arr[i] = sc.nextInt();
int total = 0;
j++)
total++;
2b)
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Program2b{
q2.add(x);
while (!q1.isEmpty()) {
q2.add(q1.remove());
q1 = q2;
q2 = temp;
if (q1.isEmpty())
{ System.out.println("Stack is empty!");
return -1;
return q1.remove();
if (q1.isEmpty())
{ System.out.println("Stack is empty!");
return -1;
return q1.peek();
}
public boolean isEmpty()
{ return q1.isEmpty();
{ if (q1.isEmpty()) {
System.out.println("Stack is empty!");
return;
do {
choice = sc.nextInt();
switch (choice) {
case 1:
value = sc.nextInt();
stack.push(value);
break;
case 2:
if (popped != -1)
System.out.println("Popped: " + popped);
break;
case 3:
if (top != -1)
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
sc.close();
3a)
import java.util.HashSet;
import java.util.Scanner;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
if (seen.contains(current.data))
{ prev.next = current.next;
} else {
seen.add(current.data);
prev = current;
current = current.next;
return head;
head = head.next;
System.out.println();
int n = sc.nextInt();
if (n == 0)
{ System.out.println("Empty
list."); return;
current = current.next;
printList(head);
head = removeDuplicates(head);
printList(head);
3b)
import java.util.Scanner;
if (arr[mid] == target) {
return mid;
{ high = mid - 1;
} else {
low = mid + 1;
} else {
{ low = mid + 1;
} else {
high = mid - 1;
return -1;
int n = sc.nextInt();
if (result == -1) {
} else {
4a)
import java.util.Scanner;
class Node {
int data;
Node next;
Node(int data)
{ this.data = data;
next = null;
first = first.next;
if (first == null)
{ head = head.next;
return head;
{ first = first.next;
second = second.next;
second.next = second.next.next;
return head;
head = head.next;
System.out.println();
int n = sc.nextInt();
if (n == 0) {
System.out.println("List is empty.");
return;
current = current.next;
printList(head);
System.out.print("List after deleting " + positionFromEnd + "th node from the end: ");
printList(head);
4b)
import java.util.Arrays;
import java.util.Scanner;
{ Arrays.sort(arr);
{ return num;
return -1;
{ Arrays.sort(arr);
{ if (arr[i] <= x) {
floor = arr[i];
break;
return floor;
int n = sc.nextInt();
arr[i] = sc.nextFloat();
if (ceil != -1) {
} else {
if (floor != -1) {
} else {
5a)
import java.util.Scanner;
{ int n = arr.length;
return arr[i];
int n = sc.nextInt();
arr[i] = sc.nextInt();
5b)
import java.util.Scanner;
class LinkedList {
Node head;
{ int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
if (head == null) {
head = newNode;
return;
{ last = last.next;
last.next = newNode;
{ next = current.next;
current.next = prev;
prev = current;
current = next;
head = prev;
System.out.println();
int n = sc.nextInt();
list.append(data);
list.printList();
list.reverse();
list.printList();
6a)
import java.util.HashMap;
import java.util.Scanner;
if (map.containsKey(complement)) {
map.put(nums[i], i);
int n = sc.nextInt();
nums[i] = sc.nextInt();
if (result.length == 0) {
} else {
System.out.println("Indices of the two numbers: [" + result[0] + ", " + result[1] + "]");
}
6b)
import java.util.Scanner;
{ int data;
Node next;
curr = curr.next;
return false;
tail = tail.next;
return head;
}
int n = sc.nextInt();
Recursion
import java.util.Scanner;
{ int data;
Node next;
tail = tail.next;
return head;
int n = sc.nextInt();
}}
7a)
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
int n = sc.nextInt();
int x = sc.nextInt();
System.out.println();
7b)
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
{ if (q.isEmpty()) {
return;
reverseQueue(q);
q.offer(front);
int n = sc.nextInt();
queue.offer(sc.nextInt());
System.out.println(queue);
reverseQueue(queue);
System.out.println(queue);
8a)
import java.util.Scanner;
result.append(str.charAt(0));
{ result.append(str.charAt(i));
return result.toString();
8b)
import java.util.Scanner;
import java.util.Stack;
while (!input.isEmpty())
{ input.push(tempStack.pop());
}
tempStack.push(temp);
return tempStack;
int n = sc.nextInt();
stack.push(sc.nextInt());
while (!sorted.isEmpty()) {
9a)
import java.util.Scanner;
{ int totalSum = 0;
int leftSum = 0;
{ totalSum -= arr[i];
if (leftSum == totalSum)
{ return I;
leftSum += arr[i];
return -1;
int n = sc.nextInt();
arr[i] = sc.nextInt();
if (index != -1) {
} else {
}
}
9b)
import java.util.Scanner;
class Node {
int data;
Node(int data) {
this.data = data;
class BST
{ Node
root;
else
return root;
int getDiameter() {
diameterUtil(root, maxDiameter);
return maxDiameter[0];
int n = sc.nextInt();
10a)
import java.util.Scanner;
class Node {
int data;
{ data = item;
class BST
{ Node
root;
{ if (node == null) {
return node;
{ if (node == null)
return;
inorder(node.left);
inorder(node.right);
return mirrored;
do {
choice = sc.nextInt();
switch (choice)
{ case 1:
value = sc.nextInt();
break;
case 2:
tree.inorder(tree.root);
System.out.println();
break;
case 3:
mirroredTree = tree.mirrorCopy(tree.root);
tree.inorder(mirroredTree);
System.out.println();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice.");
sc.close();
10 B)
import java.util.Scanner;
return operations; }
11b) Contruct a BST and remove all half nodes Half nodes - nodes with single child
import java.util.Scanner;
class Node
{ int data;
Node left, right;
Node(int item)
{ data = item;
left = right = null;
}
}
public class DynamicBSTHalfNodeRemoval
{ public static Node insert(Node root, int key)
{
if (root == null) return new Node(key);
if (key < root.data)
root.left = insert(root.left, key);
else
root.right = insert(root.right, key);
return root;
}
public static Node removeHalfNodes(Node root)
{ if (root == null) return null;
root.left = removeHalfNodes(root.left);
root.right = removeHalfNodes(root.right);
if (root.left == null && root.right != null)
return root.right;
if (root.left != null && root.right == null)
return root.left;
return root;
}
public static void inorder(Node root)
{ if (root != null) {
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
}
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in); Node root = null;
System.out.println("Enter number of nodes to insert:");
int n = sc.nextInt();
System.out.println("Enter " + n + " values:");
for (int i = 0; i < n; i++) {
int val = sc.nextInt();
root = insert(root, val);
}
System.out.print("\nInorder before removing half nodes: ");
inorder(root);
root = removeHalfNodes(root);
System.out.print("\nInorder after removing half nodes: ");
inorder(root);
}
}
Output:
Enter number of nodes to insert:
6 Enter 6 values:
10 5 2 7 15 12
Inorder before removing half nodes: 2 5 7 10 12 15
Inorder after removing half nodes: 2 5 7 10 15
16)b)knapsack problem
import java.util.Scanner;
public class Knapsack {
public static int knapsack(int W, int[] weights, int[] values, int n)
{ int[][] dp = new int[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++)
{ if (i == 0 || w == 0) {
dp[i][w] = 0;
} else if (weights[i - 1] <= w) {
dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][W];
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the number of items: ");
int n = scanner.nextInt();
System.out.print("Enter the capacity of the knapsack: ");
int W = scanner.nextInt();
int[] weights = new int[n];
int[] values = new int[n];
System.out.println("Enter the weights and values of the items:");
for (int i = 0; i < n; i++) {
System.out.print("Weight of item " + (i + 1) + ": ");
weights[i] = scanner.nextInt();
System.out.print("Value of item " + (i + 1) + ": ");
values[i] = scanner.nextInt();
}
int maxValue = knapsack(W, weights, values, n);
System.out.println("Maximum value that can be obtained: " + maxValue);
scanner.close();
}
}
Output:
Enter the number of items: 4
Enter the capacity of the knapsack: 5
Enter the weights and values of the items:
Weight of item 1: 1
Value of item 1: 1
Weight of item 2: 3
Value of item 2: 4
Weight of item 3: 4
Value of item 3: 5
Weight of item 4: 2
Value of item 4: 3
Maximum value that can be obtained: 7
18a)kadane algorithm
import java.util.Scanner;
public class KadanesAlgorithm {
public static int maxSubArraySum(int[] arr)
{ int maxSoFar = arr[0];
int maxEndingHere = arr[0];
for (int i = 1; i < arr.length; i++) {
maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
public static void main(String[] args)
{ Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int maxSum = maxSubArraySum(arr);
System.out.println("Maximum Subarray Sum = " + maxSum);
}
}
Output:
Enter number of elements: 8
Enter array elements:
-2 -3 4 -1 -2 1 5 -3
Maximum Subarray Sum = 7
18b) traversals -inorder,preorder,postorder
import java.util.Scanner;
class Node
{ int data;
Node left, right;
Node(int item)
{ data = item;
left = right = null;
}
}
public class BinaryTreeTraversals
{ public static void inorder(Node root)
{
if (root != null)
{ inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
}
public static void preorder(Node root)
{ if (root != null) {
System.out.print(root.data + " ");
preorder(root.left);
preorder(root.right);
}
}
public static void postorder(Node root)
{ if (root != null) {
postorder(root.left);
postorder(root.right);
System.out.print(root.data + " ");
}
}
public static Node insert(Node root, int key)
{ if (root == null) return new Node(key);
if (key < root.data)
root.left = insert(root.left, key);
else
root.right = insert(root.right, key);
return root;
}
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in); Node root = null;
System.out.print("Enter number of nodes: ");
int n = sc.nextInt();
System.out.println("Enter " + n + " node values:");
for (int i = 0; i < n; i++) {
int val = sc.nextInt();
root = insert(root, val); // building a BST for simplicity
}
System.out.print("\nInorder Traversal: ");
inorder(root);
System.out.print("\nPreorder Traversal: ");
preorder(root);
System.out.print("\nPostorder Traversal: ");
postorder(root);
}
}
Output:
Enter number of nodes: 5
Enter 5 node values:
10 5 20 3 7
Inorder Traversal: 3 5 7 10 20
Preorder Traversal: 10 5 3 7 20
Postorder Traversal: 3 7 5 20 10
20) a) given array sum of two numbers in array is equal to third numbers (triplet program)
input array:{3,1,17,19,21,2} Output array:19,21,2 Input array:{3,1,17,19,21,0} Triplet not
exists
import java.util.Scanner;
public class TripletCheckerDynamic
{ public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements in the array:");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
checkTriplet(arr);
}
public static void checkTriplet(int[] arr)
{ boolean found = false;
int length = arr.length;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++)
{ for (int k = 0; k < length; k++)
{
if (k != i && k != j && arr[i] + arr[j] == arr[k])
{ System.out.println(arr[i] + ", " + arr[j] + ", " + arr[k]);
found = true;
return; // Stop after finding the first triplet
}
}
}
}
if (!found) {
System.out.println("Triplet not exists");
}
}
}
Output:
Enter the number of elements in the array:
6
Enter the elements of the array:
3 1 17 19 21 2
20)b) build code to implement DFS using adjacency list without recursion
import java.util.*;
public class DFSWithoutRecursionDynamic
{ public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of nodes in the graph:");
int nodes = scanner.nextInt();
Map<Integer, List<Integer>> graph = new HashMap<>();
System.out.println("Enter the edges in the graph (as pairs of nodes):");
System.out.println("Type '-1 -1' to stop entering edges.");
while (true) {
int from = scanner.nextInt();
int to = scanner.nextInt();
if (from == -1 && to == -1) break;
graph.putIfAbsent(from, new ArrayList<>());
graph.get(from).add(to); graph.putIfAbsent(to,
new ArrayList<>()); graph.get(to).add(from);
}
System.out.println("Enter the starting node for DFS:");
int startNode = scanner.nextInt();
System.out.println("DFS Traversal:");
dfs(startNode, graph);
}
public static void dfs(int startNode, Map<Integer, List<Integer>> graph)
{ Stack<Integer> stack = new Stack<>();
Set<Integer> visited = new HashSet<>();
stack.push(startNode);
visited.add(startNode);
while (!stack.isEmpty()) {
int currentNode = stack.pop();
System.out.print(currentNode + " ");
List<Integer> neighbors = graph.getOrDefault(currentNode, new ArrayList<>());
for (int neighbor : neighbors) {
if (!visited.contains(neighbor))
{ stack.push(neighbor);
visited.add(neighbor);
}
}
}
}
}
Output:
Enter the number of nodes in the graph:5
Enter the edges in the graph (as pairs of nodes):
01
02
13
14
-1 -1
Enter the starting node for DFS:0
DFS Traversal:0 2 1 4 3
20a)
import java.util.*;
public class Program21a {
public static int distributeCandies(int[] rankings)
{ int n = rankings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1);
for (int i = 1; i < n; i++) {
if (rankings[i] > rankings[i - 1])
{ candies[i] = candies[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--) {
if (rankings[i] > rankings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
int totalCandies = Arrays.stream(candies).sum();
return totalCandies;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of students: ");
int n = scanner.nextInt();
int[] rankings = new int[n];
System.out.println("Enter rankings of students:");
for (int i = 0; i < n; i++) {
rankings[i] = scanner.nextInt();
}
int result = distributeCandies(rankings);
System.out.println("Minimum candies required: " + result);
scanner.close();
}
}
Output:
Enter number of students: 6
Enter rankings of students:
122342
Minimum candies required: 10
21b)
import java.util.*;
public class Program21b {
private static void dfs(int node, List<List<Integer>> adjList, boolean[] visited)
{ visited[node] = true;
System.out.print(node + " ");
for (int neighbor : adjList.get(node))
{ if (!visited[neighbor]) {
dfs(neighbor, adjList, visited);
}
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of vertices: ");
int V = scanner.nextInt();
System.out.print("Enter number of edges: ");
int E = scanner.nextInt();
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < V; i++) {
adjList.add(new ArrayList<Integer>()); // Explicitly specify Integer type
}
System.out.println("Enter edges (format: u v):");
for (int i = 0; i < E; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adjList.get(u).add(v);
adjList.get(v).add(u);
}
boolean[] visited = new boolean[V];
System.out.println("DFS Traversal starting from node 0:");
dfs(0, adjList, visited);
scanner.close();
}
}
Output:
Enter number of vertices: 5
Enter number of edges: 4
Enter edges (format: u v):
01
02
13
14
DFS Traversal starting from node 0:
01342
22a)
import java.util.Scanner;
public class Program22a {
public static int countWays(int n)
{ if (n < 0) return 0;
if (n == 0) return 1;
int[] dp = new int[n + 1];
dp[0] = 1;
if (n >= 1) dp[1] = 1;
if (n >= 2) dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
}
return dp[n];
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the number of stairs: ");
int n = scanner.nextInt();
int ways = countWays(n);
System.out.println("Number of ways to climb " + n + " stairs: " + ways);
scanner.close();
}
}
Output:
Enter the number of stairs: 5
Number of ways to climb 5 stairs: 13
22b)
import java.util–.*;
public class Program22b {
private static void dfs(int node, List<List<Integer>> adjList, boolean[] visited)
{ visited[node] = true;
System.out.print(node + " ");
for (int neighbor : adjList.get(node))
{ if (!visited[neighbor]) {
dfs(neighbor, adjList, visited);
}
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of vertices: ");
int V = scanner.nextInt();
System.out.print("Enter number of edges: ");
int E = scanner.nextInt();
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < V; i++) {
adjList.add(new ArrayList<Integer>());
}
System.out.println("Enter edges (format: u v):");
for (int i = 0; i < E; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adjList.get(u).add(v);
adjList.get(v).add(u);
}
boolean[] visited = new boolean[V];
System.out.println("DFS Traversal starting from node 0:");
dfs(0, adjList, visited);
scanner.close();
}
}
Output:
Enter number of vertices: 5
Enter number of edges: 4
Enter edges:
01
02
13
24
23a)
import java.util.Scanner;
public class Program23a {
public static int lcs(String str1, String str2)
{ int m = str1.length();
int n = str2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1))
{ dp[i][j] = 1 + dp[i - 1][j - 1]; // Match
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter second string: ");
String str2 = scanner.nextLine();
int result = lcs(str1, str2);
System.out.println("Length of Longest Common Subsequence: " + result);
scanner.close();
}
}
Output:
Enter first string: ABCDGH
Enter second string: AEDFHR
Length of Longest Common Subsequence: 3
23b)
import java.util.*;
public class Program23b {
private static void dfs(int node, List<List<Integer>> adjList, boolean[] visited)
{ visited[node] = true;
System.out.print(node + " ");
for (int neighbor : adjList.get(node))
{ if (!visited[neighbor]) {
dfs(neighbor, adjList, visited);
}
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of vertices: ");
int V = scanner.nextInt();
System.out.print("Enter number of edges: ");
int E = scanner.nextInt();
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < V; i++) {
adjList.add(new ArrayList<>());
}
System.out.println("Enter edges (format: u v):");
for (int i = 0; i < E; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adjList.get(u).add(v);
adjList.get(v).add(u); // Assuming undirected graph
}
boolean[] visited = new boolean[V];
System.out.print("Enter the starting node for DFS: ");
int startNode = scanner.nextInt();
System.out.println("DFS Traversal:");
dfs(startNode, adjList, visited);
scanner.close();
}
}
Output:
Enter number of vertices: 5
Enter number of edges: 4
Enter edges:
01
02
13
24
Enter the starting node for DFS: 0
DFS Traversal:
01324
24a)
import java.util.*;
public class Program24a {
public static List<List<Integer>> findTriplets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums); // Sort array
int n = nums.length;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = n - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0)
{ left++;
} else {
right--;
}
}
}
return result;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] nums = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
List<List<Integer>> result = findTriplets(nums);
System.out.println("Triplets with sum zero: " + result);
scanner.close();
}
}
Output:
Enter number of elements: 6
Enter array elements:
-1 0 1 2 -1 -4
Triplets with sum zero: [[-1, -1, 2], [-1, 0, 1]]
24b)
import java.util.*;
public class Program24b {
public static void bfs(int startNode, int[][] adjMatrix, int V)
{ boolean[] visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
visited[startNode] = true;
queue.add(startNode);
System.out.println("BFS Traversal:");
while (!queue.isEmpty())
{ int node = queue.poll();
System.out.print(node + " ");
for (int neighbor = 0; neighbor < V; neighbor++) {
if (adjMatrix[node][neighbor] == 1 && !visited[neighbor])
{ visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of vertices: ");
int V = scanner.nextInt();
int[][] adjMatrix = new int[V][V];
System.out.print("Enter number of edges: ");
int E = scanner.nextInt();
System.out.println("Enter edges (format: u v):");
for (int i = 0; i < E; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1; // Assuming an undirected graph
}
System.out.print("Enter the starting node for BFS: ");
int startNode = scanner.nextInt();
bfs(startNode, adjMatrix, V);
scanner.close();
}
}
Output:
Enter number of vertices: 5
Enter number of edges: 4
Enter edges:
01
02
13
24
Enter the starting node for BFS: 0
BFS Traversal:
01234
25a)
import java.util.*;
public class Program25a {
public static int findMinPlatforms(int[] arrival, int[] departure)
{ Arrays.sort(arrival);
Arrays.sort(departure);
int platforms = 1, maxPlatforms = 1;
int i = 1, j = 0; // i -> arrival, j -> departure
int n = arrival.length;
while (i < n && j < n) {
if (arrival[i] <= departure[j]) {
platforms++; // New train arrives, need more platforms
i++;
} else {
platforms--; // Train departs, free up a platform
j++;
}
maxPlatforms = Math.max(maxPlatforms, platforms);
}
return maxPlatforms;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of trains: ");
int n = scanner.nextInt();
int[] arrival = new int[n];
int[] departure = new int[n];
System.out.println("Enter arrival times:");
for (int i = 0; i < n; i++) {
arrival[i] = scanner.nextInt();
}
System.out.println("Enter departure times:");
for (int i = 0; i < n; i++) {
departure[i] = scanner.nextInt();
}
int result = findMinPlatforms(arrival, departure);
System.out.println("Minimum platforms required: " + result);
scanner.close();
}
}
Output:
Enter number of trains: 6
Enter arrival times:
900 940 950 1100 1500 1800
Enter departure times:
910 1200 1120 1130 1900 2000
Minimum platforms required: 3
25b)
import java.util.*;
public class Program25b {
public static void bfs(int startNode, List<List<Integer>> adjList, int V) { boolean[]
visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
visited[startNode] = true;
queue.add(startNode);
System.out.println("BFS Traversal:");
while (!queue.isEmpty())
{ int node = queue.poll();
System.out.print(node + " ");
for (int neighbor : adjList.get(node))
{ if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of vertices: ");
int V = scanner.nextInt();
System.out.print("Enter number of edges: ");
int E = scanner.nextInt();
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < V; i++) {
adjList.add(new ArrayList<Integer>());
}
System.out.println("Enter edges (format: u v):");
for (int i = 0; i < E; i++)
{ int u = scanner.nextInt();
int v = scanner.nextInt();
adjList.get(u).add(v);
adjList.get(v).add(u); // Assuming an undirected graph
}
System.out.print("Enter the starting node for BFS: ");
int startNode = scanner.nextInt();
bfs(startNode, adjList, V);
scanner.close();
}
}
Output:
Enter number of vertices: 5
Enter number of edges: 4
Enter edges:
01
02
13
24
Enter the starting node for BFS: 0
BFS Traversal:
01234
26a)
import java.util.Scanner;
public class Program26a {
public static String alternateStrings(String str1, String str2)
{ StringBuilder result = new StringBuilder();
int len1 = str1.length(), len2 = str2.length();
int maxLen = Math.max(len1, len2);
for (int i = 0; i < maxLen; i++) {
if (i < len1) result.append(str1.charAt(i));
if (i < len2) result.append(str2.charAt(i));
}
return result.toString();
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter second string: ");
String str2 = scanner.nextLine();
String result = alternateStrings(str1, str2);
System.out.println("Alternating merged string: " + result);
scanner.close();
}
}
Output:
Enter first string: ABC
Enter second string: 123
Alternating merged string: A1B2C3
Enter first string: Hello
Enter second string: 123
Alternating merged string: H1e2l3lo
26b)
import java.util.*;
public class Program26b {
public static boolean isBalanced(String str)
{ Stack<Character> stack = new
Stack<>(); for (char ch : str.toCharArray())
{
if (ch == '(' || ch == '{' || ch == '[')
{ stack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']')
{ if (stack.isEmpty()) return false;
char top = stack.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter a string with parentheses: ");
String input = scanner.nextLine();
boolean result = isBalanced(input);
System.out.println("Balanced: " + result);
scanner.close();
}
}
Output:
Enter a string with parentheses: ({)
Balanced: false
Enter a string with parentheses: ({})
Balanced: true
Enter a string with parentheses: {[()]}
Balanced: true
Enter a string with parentheses: ({[)])
Balanced: false
27a)
import java.util.*;
public class Program27a {
public static List<List<Integer>> fourSum(int[] nums, int target)
{ List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums); // Sort the array
int n = nums.length;
for (int i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int left = j + 1, right = n - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++; // Skip duplicates
while (left < right && nums[right] == nums[right - 1]) right--; // Skip duplicates
left++;
right--;
} else if (sum < target)
{ left++;
} else {
right--;
}
}
}
}
return result;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] nums = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
System.out.print("Enter target sum: ");
int target = scanner.nextInt();
List<List<Integer>> result = fourSum(nums, target);
System.out.println("Quadruplets with sum " + target + ": " + result);
scanner.close();
}
}
Output:
Enter number of elements: 6
Enter array elements:
1 0 -1 0 -2 2
Enter target sum: 0
Quadruplets with sum 0: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
27b)
import java.util.*;
public class Program27b {
public static void deleteMiddle(Stack<Integer> stack, int midIndex)
{ if (stack.size() == midIndex + 1) {
stack.pop();
return;
}
int temp = stack.pop();
deleteMiddle(stack, midIndex);
stack.push(temp);
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in); Stack<Integer> stack =
new Stack<>();
System.out.print("Enter number of elements in the stack: ");
int n = scanner.nextInt();
System.out.println("Enter stack elements:");
for (int i = 0; i < n; i++) {
stack.push(scanner.nextInt());
}
int midIndex = n / 2;
deleteMiddle(stack, midIndex);
System.out.println("Stack after deleting middle element: " + stack);
scanner.close();
}
}
Output:
Enter number of elements in the stack: 5
Enter stack elements:
12345
Stack after deleting middle element: [1, 2, 4, 5]
28a)
import java.util.*;
public class Program28a {
public static int findMaxInQueue(Queue<Integer> queue) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (int num : queue) {
maxHeap.add(num);
}
return maxHeap.peek();
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
Queue<Integer> queue = new LinkedList<>();
System.out.print("Enter number of elements in the queue: ");
int n = scanner.nextInt();
System.out.println("Enter queue elements:");
for (int i = 0; i < n; i++) {
queue.add(scanner.nextInt());
}
int maxElement = findMaxInQueue(queue);
System.out.println("Maximum element in queue: " + maxElement);
scanner.close();
}
}
Output:
Enter number of elements in the queue: 6
Enter queue elements:
317295
Maximum element in queue: 9
28b)
import java.util.*;
public class Program28b {
static class StackUsingQueue {
Queue<Integer> queue1 = new LinkedList<>();
Queue<Integer> queue2 = new LinkedList<>();
public void push(int x) {
queue1.add(x);
}
public int pop() {
if (queue1.isEmpty())
{ System.out.println("Stack is empty!");
return -1;
}
while (queue1.size() > 1)
{ queue2.add(queue1.poll());
}
int popped = queue1.poll();
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
return popped;
}
public int top() {
if (queue1.isEmpty())
{ System.out.println("Stack is empty!");
return -1;
}
while (queue1.size() > 1)
{ queue2.add(queue1.poll());
}
int topElement = queue1.peek();
queue2.add(queue1.poll());
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
return topElement;
}
public boolean isEmpty()
{ return queue1.isEmpty();
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
StackUsingQueue stack = new StackUsingQueue();
System.out.print("Enter number of elements to push into stack: ");
int n = scanner.nextInt();
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
stack.push(scanner.nextInt());
}
System.out.println("Top element: " + stack.top());
System.out.println("Popped element: " + stack.pop());
System.out.println("Top element after pop: " + stack.top());
scanner.close();
}
}
Output:
Enter number of elements to push into stack: 5
Enter elements:
10 20 30 40 50
Top element: 50
Popped element: 50
Top element after pop: 40
29a)
import java.util.*;
public class Program29a {
public static int uniquePathsWithObstacles(int[][] grid)
{ int m = grid.length, n = grid[0].length;
if (grid[0][0] == 1 || grid[m - 1][n - 1] == 1) return 0;
int[][] dp = new int[m][n];
dp[0][0] = 1;
for (int i = 0; i < m; i++)
{ for (int j = 0; j < n; j++)
{
if (grid[i][j] == 1) {
dp[i][j] = 0;
} else {
if (i > 0) dp[i][j] += dp[i - 1][j];
if (j > 0) dp[i][j] += dp[i][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of rows: ");
int m = scanner.nextInt();
System.out.print("Enter number of columns: ");
int n = scanner.nextInt();
int[][] grid = new int[m][n];
System.out.println("Enter grid (0 for open cell, 1 for obstacle):");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
{ grid[i][j] = scanner.nextInt();
}
}
int result = uniquePathsWithObstacles(grid);
System.out.println("Number of unique paths: " + result);
scanner.close();
}
}
Output:
Enter number of rows: 3
Enter number of columns: 3
Enter grid:
000
010
000
Number of unique paths: 2
29b)
import java.util.*;
public class Program29b {
public static void reverseQueue(Queue<Integer> queue)
{ Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty())
{ stack.push(queue.poll());
}
while (!stack.isEmpty())
{ queue.add(stack.pop());
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
Queue<Integer> queue = new LinkedList<>();
System.out.print("Enter number of elements in the queue: ");
int n = scanner.nextInt();
System.out.println("Enter queue elements:");
for (int i = 0; i < n; i++) {
queue.add(scanner.nextInt());
}
reverseQueue(queue);
System.out.println("Queue after reversal: " + queue);
scanner.close();
}
}
Output:
Enter number of elements in the queue: 5
Enter queue elements:
12345
Queue after reversal: [5, 4, 3, 2, 1]
30a)
import java.util.*;
public class Program30a {
public static int[] removeDuplicates(int[] nums)
{ LinkedHashSet<Integer> set = new LinkedHashSet<>();
for (int num : nums) {
set.add(num);
}
int[] uniqueArray = new int[set.size()];
int i = 0;
for (int num : set)
{ uniqueArray[i++] = num;
}
return uniqueArray;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] nums = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
int[] uniqueArray = removeDuplicates(nums);
System.out.println("Unique array: " + Arrays.toString(uniqueArray));
System.out.println("New length: " + uniqueArray.length);
scanner.close();
}
}
Output:
Enter number of elements: 7
Enter array elements:
1223445
Unique array: [1, 2, 3, 4, 5]
New length: 5
30b)
import java.util.*;
public class Program30b
{ static class MinStack {
Stack<Integer> mainStack = new Stack<>();
Stack<Integer> minStack = new Stack<>();
public void push(int x) {
mainStack.push(x);
if (minStack.isEmpty() || x <= minStack.peek())
{ minStack.push(x);
}
}
public void pop() {
if (!mainStack.isEmpty()) {
int popped = mainStack.pop();
if (popped == minStack.peek())
{ minStack.pop();
}
}
}
public int getMin() {
return minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in); MinStack stack = new
MinStack();
System.out.print("Enter number of elements in the stack: ");
int n = scanner.nextInt();
System.out.println("Enter stack elements:");
for (int i = 0; i < n; i++) {
stack.push(scanner.nextInt());
}
System.out.println("Minimum element in stack: " + stack.getMin());
scanner.close();
}
}
Output:
Enter number of elements in the stack: 5
Enter stack elements:
35214
Minimum element in stack: 1
31a)
import java.util.Scanner;
public class Program31a {
public static int findMissingTerm(int[] sequence)
{ int n = sequence.length;
int r = sequence[1] / sequence[0];
for (int i = 1; i < n; i++) {
if (sequence[i] != sequence[i - 1] * r)
{ return sequence[i - 1] * r;
}
}
return -1;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = scanner.nextInt();
int[] sequence = new int[n];
System.out.println("Enter logarithmic sequence (one missing term):");
for (int i = 0; i < n; i++) {
sequence[i] = scanner.nextInt();
}
int missingTerm = findMissingTerm(sequence);
System.out.println("Missing term: " + missingTerm);
scanner.close();
}
}
Output:
Enter number of terms: 5
Enter logarithmic sequence:
2 6 _ 54 162
Missing term: 18
31b)
import java.util.*;
public class Program31b
{ static class MinStack {
Stack<Integer> stack = new Stack<>();
int minElement;
public void push(int x)
{ if (stack.isEmpty())
{
minElement = x;
stack.push(x);
} else {
if (x < minElement)
{ stack.push(2 * x -
minElement); minElement = x;
} else {
stack.push(x);
}
}
}
public void pop() {
if (!stack.isEmpty()) {
int popped = stack.pop();
if (popped < minElement) {
minElement = 2 * minElement - popped;
}
}
}
public int getMin() {
return stack.isEmpty() ? Integer.MAX_VALUE : minElement;
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
MinStack stack = new MinStack();
System.out.print("Enter number of elements in the stack: ");
int n = scanner.nextInt();
System.out.println("Enter stack elements:");
for (int i = 0; i < n; i++) {
stack.push(scanner.nextInt());
}
System.out.println("Minimum element in stack: " + stack.getMin());
scanner.close();
}
}
Output:
Enter number of elements in the stack: 5
Enter stack elements:
35214
Minimum element in stack: 1
import java.util.Arrays;
import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;
33A)
import java.util.Scanner;
// Function to find the first occurrence of the element using binary search
public static int firstOccurrence(int[] arr, int target) {
int low = 0, high = arr.length - 1;
int result = -1;
if (arr[mid] == target) {
result = mid;
high = mid - 1; // Keep searching in the left half
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
// Function to find the last occurrence of the element using binary search
public static int lastOccurrence(int[] arr, int target) {
int low = 0, high = arr.length - 1;
int result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
result = mid;
low = mid + 1; // Keep searching in the right half
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
sc.close();
}
}
33B)
import java.util.Scanner;
// Function to find the first occurrence of the element using binary search
public static int firstOccurrence(int[] arr, int target) {
int low = 0, high = arr.length - 1;
int result = -1;
if (arr[mid] == target) {
result = mid;
high = mid - 1; // Keep searching in the left half
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
// Function to find the last occurrence of the element using binary search
public static int lastOccurrence(int[] arr, int target) {
int low = 0, high = arr.length - 1;
int result = -1;
if (arr[mid] == target) {
result = mid;
low = mid + 1; // Keep searching in the right half
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
sc.close();
}
}
34a)
import java.util.Scanner;
public class Program34a {
public static int ternarySearch(int[] arr, int low, int high, int target)
{ if (low > high) return -1;
int mid1 = low + (high - low) / 3;
int mid2 = high - (high - low) / 3;
if (arr[mid1] == target) return mid1;
if (arr[mid2] == target) return mid2;
if (target < arr[mid1]) {
return ternarySearch(arr, low, mid1 - 1, target);
} else if (target > arr[mid2]) {
return ternarySearch(arr, mid2 + 1, high, target);
} else {
return ternarySearch(arr, mid1 + 1, mid2 - 1, target);
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter sorted array elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter target element: ");
int target = scanner.nextInt();
int result = ternarySearch(arr, 0, n - 1, target);
System.out.println(result != -1 ? "Element found at index: " + result : "Element not found");
scanner.close();
}
}
Output:
Enter number of elements: 6
Enter sorted array elements:
123456
Enter target element: 4
Element found at index: 3
34b)
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; this.next = null; }
}
public class Program34b {
public static boolean isPalindrome(ListNode head) {
Stack<Integer> stack = new Stack<>();
ListNode temp = head;
while (temp != null)
{ stack.push(temp.val);
temp = temp.next;
}
temp = head;
while (temp != null) {
if (temp.val != stack.pop()) return false;
temp = temp.next;
}
return true;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements in linked list: ");
int n = scanner.nextInt();
System.out.println("Enter linked list elements:");
ListNode head = null, tail = null;
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
ListNode newNode = new ListNode(value);
if (head == null) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
}
System.out.println("Is the linked list a palindrome? " + isPalindrome(head));
scanner.close();
}
}
Output:
Enter number of elements in linked list: 5
Enter linked list elements:
12321
Is the linked list a palindrome? True
35a)
import java.util.*;
public class Program35a {
public static int[] sortedSquares(int[] arr)
{ int n = arr.length;
int[] result = new int[n];
int left = 0, right = n - 1;
int index = n - 1;
while (left <= right) {
int leftSquare = arr[left] * arr[left];
int rightSquare = arr[right] * arr[right];
if (leftSquare > rightSquare) {
result[index--] = leftSquare;
left++;
} else {
result[index--] = rightSquare;
right--;
}
}
return result;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter sorted array elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int[] result = sortedSquares(arr);
System.out.println("Sorted array after squaring: " + Arrays.toString(result));
scanner.close();
}
}
Output:
Enter number of elements: 6
Enter sorted array elements:
-4 -2 0 1 3 5
Sorted array after squaring: [0, 1, 4, 9, 16, 25]
35b)
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; this.next = null; }
}
public class Program35b {
public static ListNode removeNthFromEnd(ListNode head, int n)
{ ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy, fast = dummy;
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
while (fast != null)
{ slow =
slow.next; fast =
fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements in linked list: ");
int n = scanner.nextInt();
System.out.println("Enter linked list elements:");
ListNode head = null, tail = null;
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
ListNode newNode = new ListNode(value);
if (head == null) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
}
System.out.print("Enter Nth element to remove from end: ");
int removePosition = scanner.nextInt();
head = removeNthFromEnd(head, removePosition);
System.out.print("Linked list after deletion: ");
ListNode temp = head;
while (temp != null)
{ System.out.print(temp.val + " ");
temp = temp.next;
}
scanner.close();
}
}
Output:
Enter number of elements in linked list: 5
Enter linked list elements:
12345
Enter Nth element to remove from end: 2
Linked list after deletion: 1 2 3 5
36a)
import java.util.*;
public class Program36a {
public static void paritySort(int[] arr)
{ int left = 0, right = arr.length - 1;
while (left < right) {
if (arr[left] % 2 == 0)
{ left++;
} else if (arr[right] % 2 != 0)
{ right--;
} else {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
paritySort(arr);
System.out.println("Sorted array (Even first, Odd last): " + Arrays.toString(arr));
scanner.close();
}
}
Output:
Enter number of elements: 6
Enter array elements:
312456
Sorted array (Even first, Odd last): [6, 4, 2, 1, 5, 3]
36b)
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class Program36b {
public static TreeNode insert(TreeNode root, int val)
{ if (root == null) return new TreeNode(val);
if (val < root.val) root.left = insert(root.left, val);
else root.right = insert(root.right, val);
return root;
}
public static int diameter(TreeNode root)
{ int[] diameter = new int[1];
height(root, diameter);
return diameter[0];
}
private static int height(TreeNode node, int[] diameter)
{ if (node == null) return 0;
int leftHeight = height(node.left, diameter);
int rightHeight = height(node.right, diameter);
diameter[0] = Math.max(diameter[0], leftHeight + rightHeight);
return 1 + Math.max(leftHeight, rightHeight);
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in); TreeNode root = null;
System.out.print("Enter number of nodes in BST: ");
int n = scanner.nextInt();
System.out.println("Enter BST elements:");
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
root = insert(root, value);
}
int result = diameter(root);
System.out.println("Diameter of the BST: " + result);
scanner.close();
}
}
Output:
Enter number of nodes in BST: 6
Enter BST elements:
538249
Diameter of the BST: 3
37a)
import java.util.*;
public class Program37a {
public static int findLIS(int[] arr)
{ int n = arr.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxLIS = 1;
for (int i = 1; i < n; i++)
{ for (int j = 0; j < i; j++)
{
if (arr[i] > arr[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxLIS = Math.max(maxLIS, dp[i]);
}
return maxLIS;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int result = findLIS(arr);
System.out.println("Length of Longest Increasing Subsequence: " + result);
scanner.close();
}
}
Output:
Enter number of elements: 6
Enter array elements:
10 22 9 33 21 50
Length of Longest Increasing Subsequence: 4
37b)
import java.util.*;
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isEndOfWord;
}
public class Program37b
{ private TrieNode root;
public Program37b() {
root = new TrieNode();
}
public void insert(String word)
{ TrieNode node = root;
for (char ch : word.toCharArray())
{ node.children.putIfAbsent(ch, new TrieNode());
node = node.children.get(ch);
}
node.isEndOfWord = true;
}
public String longestCommonPrefix()
{ TrieNode node = root;
StringBuilder prefix = new StringBuilder();
while (node.children.size() == 1 && !node.isEndOfWord)
{ char ch = node.children.keySet().iterator().next();
prefix.append(ch);
node = node.children.get(ch);
}
return prefix.toString();
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in); Program37b trie = new
Program37b();
System.out.print("Enter number of words: ");
int n = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter words:");
for (int i = 0; i < n; i++) {
trie.insert(scanner.nextLine());
}
System.out.println("Longest Common Prefix: " + trie.longestCommonPrefix());
scanner.close();
}
}
Output:
Enter number of words: 4
Enter words:
flower
flow
flight
flame
Longest Common Prefix: fl
38 a)
import java.util.*;
Arrays.fill(inc, 1);
Arrays.fill(dec, 1);
int max = 0;
for (int i = 0; i < n; i++)
if (inc[i] > 1 && dec[i] > 1)
max = Math.max(max, inc[i] + dec[i] - 1);
return max;
}
38 b)
import java.util.*;
39 A
import java.util.*;
39B
import java.util.*;
import java.util.Scanner;
class Solution {
public int maxProfit(int[] prices) {
int s = 0, p = 0, d = 0, n = prices.length;
for (int i = n - 1; i >= 0; i--) {
if (s < prices[i])
s = prices[i];
d = s - prices[i];
if (p < d)
p = d;
}
return p;
}
}
40 b)
import java.util.*;
class TreeNode
{
int val;
TreeNode left, right;
TreeNode(int val)
{
this.val = val;
}
}
public class Program41b {
public static int countHalfNodes(TreeNode root)
{
if (root == null) return 0;
int count = 0;
if ((root.left == null && root.right != null) || (root.left != null && root.right ==
null))
{
count = 1;
}
return count + countHalfNodes(root.left) + countHalfNodes(root.right);
}
public static TreeNode insert(TreeNode root, int val)
{
if (root == null) return new TreeNode(val);
if (val < root.val) root.left = insert(root.left, val);
else root.right = insert(root.right, val);
return root;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TreeNode root = null;
System.out.print("Enter number of nodes in BST: ");
int n = scanner.nextInt();
System.out.println("Enter BST elements:");
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
root = insert(root, value);
}
int result = countHalfNodes(root);
System.out.println("Number of half nodes in BST: " + result);
}
}
Output:-
Enter number of nodes in BST: 5
Enter BST elements:
52691
Number of half nodes in BST: 2
41a)
import java.util.*;
public class Program41a {
public static int maxProfit(int[] prices)
{ if (prices.length == 0) return 0;
int minPrice = Integer.MAX_VALUE, maxProfit = 0;
for (int price : prices) {
minPrice = Math.min(minPrice, price);
maxProfit = Math.max(maxProfit, price - minPrice);
}
return maxProfit;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter number of days: ");
int n = scanner.nextInt();
int[] prices = new int[n];
System.out.println("Enter stock prices:");
for (int i = 0; i < n; i++) {
prices[i] = scanner.nextInt();
}
int result = maxProfit(prices);
System.out.println("Maximum profit: " + result);
scanner.close();
}
}
Output:
Enter number of days: 6
Enter stock prices:
715364
Maximum profit: 5
41b)
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class Program41b {
public static int countHalfNodes(TreeNode root)
{ if (root == null) return 0;
int count = 0;
if ((root.left == null && root.right != null) || (root.left != null && root.right == null))
{ count = 1;
}
return count + countHalfNodes(root.left) + countHalfNodes(root.right);
}
public static TreeNode insert(TreeNode root, int val)
{ if (root == null) return new TreeNode(val);
if (val < root.val) root.left = insert(root.left, val);
else root.right = insert(root.right, val);
return root;
}
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in); TreeNode root = null;
System.out.print("Enter number of nodes in BST: ");
int n = scanner.nextInt();
System.out.println("Enter BST elements:");
for (int i = 0; i < n; i++) {
int value = scanner.nextInt();
root = insert(root, value);
}
int result = countHalfNodes(root);
System.out.println("Number of half nodes in BST: " + result);
scanner.close();
}
}
Output:
Enter number of nodes in BST: 6
Enter BST elements:
538249
Number of half nodes in BST: 1