competative coding with java[1]
competative coding with java[1]
Lab Manual
Name :-
Enrollment no. :-
Roll no. :-
Division :-
Year/Sem :-
Faculty :-
CERTIFICATE
This is to certify that with Enrollment no.
Enrollment No : Page | 1
Index
Sr.no Experiment title Date Marks Sign
1 Write a program for implementing
a MINSTACK which should support
operations like push, pop, overflow,
underflow, display
1. Construct a stack of N-capacity
2. Push elements
3. Pop elements
4. Top element
5. Retrieve the min element from the
stack
Enrollment No : Page | 2
6 Write a Program for finding the Product of the
three largest Distinct Elements. Use a Priority
Queue to efficiently find and remove the
largest elements
Enrollment No : Page | 3
Practical 1
Aim : Write a program for implementing a MINSTACK which should support
operations like push, pop, overflow, underflow, display
a. Construct a stack of N-capacity
a. Push elements
a. Pop elements
a. Top element
a. Retrieve the min element from the stack
Algorithm :
This Java code implements a MinStack data structure that stores integers with the ability to
retrieve the minimum element efficiently. It uses two stacks - one stack (stack) to store elements
and another stack (minStack) to keep track of the current minimum element.
• Instance Variables:
o maxSize: Maximum capacity of the stack.
o stack: A stack to store elements.
o minStack: A stack to keep track of the minimum element.
• Constructor (MinStack(int capacity)):
o Initializes maxSize to the given capacity.
o Creates empty stack and minStack.
• Methods:
o push(int element): Adds an element to the stack and updates the minimum
element in minStack if necessary.
o pop(): Removes the top element from the stack and
updates minStack accordingly.
o top(): Returns the top element of the stack without removing it.
o getMin(): Returns the current minimum element.
o display(): Displays all elements in the stack.
• Main Method:
o Creates a MinStack instance with a capacity of 5.
o Demonstrates pushing elements, popping elements, displaying the stack,
obtaining the minimum element, and getting the top element.
Algorithm :
1. Initialization:
• Create a MinStack instance minStack with a capacity of 5.
2. Push Operation:
• push(int element)
o Check if the stack is not full.
Enrollment No : Page | 4
Push the element onto the stack.
o
If minStack is empty or the element is less than or equal to the current
o
minimum, push element onto minStack.
3. Pop Operation:
• pop()
o Check if the stack is not empty.
o Pop the top element from the stack.
o If the popped element is the current minimum, pop from minStack as
well.
4. Top Operation:
• top()
o Check if the stack is not empty.
o Return the top element of the stack.
5. GetMin Operation:
• getMin()
o Check if minStack is not empty.
o Return the minimum element from minStack.
6. Display Operation:
• display()
o Print "Elements in the stack:".
o Iterate over elements in the stack and print each element.
7. Main Method Execution:
• Instantiate a MinStack object with a capacity of 5.
• Push elements (3, 5, 2, 7, 1) to the stack.
• Display elements in the stack.
• Print the minimum element in the stack.
• Pop two elements from the stack.
• Print the top element in the stack.
Code :
import java.util.*;
class MinStack {
private int maxSize;
private Stack<Integer> stack;
private Stack<Integer> minStack;
Enrollment No : Page | 5
minStack = new Stack<>();
}
stack.push(element);
if (minStack.isEmpty() || element <= minStack.peek()) {
minStack.push(element);
}
}
return stack.peek();
}
Enrollment No : Page | 6
return minStack.peek();
}
minStack.display();
minStack.pop();
minStack.pop();
Output :
Enrollment No : Page | 7
Practical 2
Aim : Write a program to deal with real-world situations where Stack data structure is
widely used
Evaluation of expression:
Stacks are used to evaluate expressions, especially in
languages that use postfix or prefix notation. Operators and operands are pushed
onto the stack, and operations are performed based on the LIFO principle.
Algorithm :
1. Initialize:
• Create an empty stack stack to store operands.
3. Final result:
• After iterating through all characters, the stack should contain only one element – the
final result of the expression.
• Pop this element from the stack and return it.
Additional points:
• The code assumes the expression is well-formed and uses valid operators and operands.
• The order of operations is followed using implicit order of precedence (multiplication
and division before addition and subtraction).
• Error handling for invalid expressions or division by zero is not implemented in this
specific code.
Example:
Enrollment No : Page | 8
• +: Pop 6 and 3, add them (9), and push the result back.
• 9: Pushed onto the stack.
• *: Pop 9 and 36, multiply them (324), and push the result back.
• No more characters.
• The stack now has only one element: 324.
Pop and return this element (324) as the result.
Code :
package LabQues;
import java.util.Stack;
for(char ch : expression.toCharArray()) {
if(Character.isDigit(ch)) {
stack.push(Character.getNumericValue(ch));
} else {
int operand2 = stack.pop();
int operand1 = stack.pop();
switch(ch) {
case '+': stack.push(operand1 + operand2); break;
case '-': stack.push(operand1 - operand2); break;
case '*': stack.push(operand1 * operand2); break;
case '/': stack.push(operand1 / operand2); break;
}
}
}
return stack.pop();
}
Enrollment No : Page | 9
Output :
Enrollment No : Page | 10
Practical 3
Aim : Write a program for finding NGE NEXT GREATER ELEMENT from an array
Algorithm :
1. Initialization:
• Create an empty stack stack to store elements.
• Create a result array result of the same size as the input array arr to store the next greater
elements.
Key points:
• The algorithm uses a stack to keep track of potential next greater elements for elements
to the left.
• It processes the array in reverse order to ensure correct NGEs are found for all elements.
• It has a time complexity of O(n) and a space complexity of O(n) due to the stack and
result array.
Code :
package LabQues;
import java.util.*;
Enrollment No : Page | 11
Stack<Integer> stack = new Stack<>();
int n = arr.length;
int[] result = new int[n];
if (stack.isEmpty()) {
result[i] = -1;
} else {
result[i] = stack.peek();
}
stack.push(arr[i]);
}
return result;
}
Output :
Enrollment No : Page | 12
Practical 4
Aim : Write a program to design a circular queue(k) which Should implement the below
functions
Enqueue
Dequeue
Front
Rear
Algorithm :
This code defines a class CircularQueue that represents a circular queue data structure. Here's
a breakdown of its key components:
• Instance Variables:
o queue: An integer array to store the elements of the circular queue.
o front: An integer representing the front index of the queue.
o rear: An integer representing the rear index of the queue.
o size: An integer representing the current size of the queue.
o capacity: An integer representing the maximum capacity of the queue.
• Constructor (CircularQueue(int k)):
o Initializes the queue with a specified capacity k.
o Initializes front to 0, rear to -1, and size to 0.
• Methods:
o enQueue(int value): Adds an element to the rear of the queue.
o deQueue(): Removes an element from the front of the queue.
o Front(): Returns the element at the front of the queue without removing it.
o Rear(): Returns the element at the rear of the queue without removing it.
o isEmpty(): Checks if the queue is empty.
o isFull(): Checks if the queue is full.
• Main Method:
o Creates an instance of CircularQueue with a capacity of 5.
o Demonstrates various operations on the circular queue like enqueue, dequeue,
checking front, checking rear, etc.
Algorithm :
1. Initialization:
• Create a CircularQueue instance cq with a capacity of 5.
2. Enqueue Operation:
• enQueue(int value)
Enrollment No : Page | 13
o Check if the queue is not full (!isFull()).
o Calculate the new rear index using circular logic.
o Place the value at the new rear index.
o Increment the size.
o Return true.
3. Dequeue Operation:
• deQueue()
o Check if the queue is not empty (!isEmpty()).
o Calculate the new front index using circular logic.
o Decrement the size.
o Return true.
4. Front Operation:
• Front()
o Check if the queue is not empty.
o Return the element at the front index.
5. Rear Operation:
• Rear()
o Check if the queue is not empty.
o Return the element at the rear index.
6. isEmpty Operation:
• isEmpty()
o Check if the size of the queue is 0.
o Return true if the queue is empty.
7. isFull Operation:
• isFull()
o Check if the size of the queue is equal to the capacity.
o Return true if the queue is full.
8. Main Method Execution:
• Instantiate a CircularQueue object with a capacity of 5.
• Perform a series of enqueuing, dequeuing, and checking operations.
• Print the results of these operations.
Code :
package LabQues;
class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;
public CircularQueue(int k) {
capacity = k;
Enrollment No : Page | 14
queue = new int[k];
front = 0;
rear = -1;
size = 0;
}
Enrollment No : Page | 15
}
Output :
Enrollment No : Page | 16
Practical 5
Aim : Write a Program for an infix expression, and convert it to postfix notation. Use a
queue to implement the Shunting Yard Algorithm for expression conversion.
Algorithm :
1. Create a method named infixToPostfix that takes an infix expression as input and
returns the corresponding postfix expression.
2. Initialize an empty string postfix to store the postfix expression.
3. Create a stack operatorStack to hold operators during the conversion process.
4. Create a HashMap precedence to store the precedence of operators (+, -, *, /, ^), where
^ has the highest precedence followed by / and *, and finally + and - with the lowest
precedence.
5. Iterate through each character c in the input infix expression:
• If c is a letter or digit, add it directly to the postfix string.
• If c is an opening parenthesis (, push it onto the operatorStack.
• If c is a closing parenthesis ), pop and append operators from operatorStack
to postfix until an opening parenthesis is encountered. Pop the opening parenthesis
as well.
• If c is an operator (+, -, *, /, ^), compare its precedence with the operator at the
top of the stack. Pop and append operators with higher or equal precedence from
operatorStack to postfix before pushing c onto the stack.
6. After processing the entire input expression, pop and append any remaining operators
from operatorStack to postfix.
7. Return the postfix expression.
8. In the main method:
• Define an example infix expression a+b*(c^d-e)^(f+g*h)-i.
• Print the infix expression.
• Call the infixToPostfix method with the infix expression and print the resulting
postfix expression.
This way, the algorithm converts an infix expression to its equivalent postfix expression by
considering operator precedence and parentheses in the input expression.
Code :
package LabQues;
import java.util.*;
public class InfixToPostfix {
Enrollment No : Page | 17
String postfix = "";
Stack<Character> operatorStack = new Stack<>();
while (!operatorStack.isEmpty()) {
postfix += operatorStack.pop();
}
return postfix;
}
Enrollment No : Page | 18
Output :
Enrollment No : Page | 19
Practical 6
Aim : Write a Program for finding the Product of the three largest Distinct Elements. Use
a Priority Queue to efficiently find and remove the largest elements
Algorithms :
Code :
package LabQues;
import java.util.*;
public class ThreeLargestProduct {
Enrollment No : Page | 20
int largest2 = pq.poll();
int largest3 = pq.poll();
Output :
Enrollment No : Page | 21
Practical 7
Algorithms :
1. Node Class:
• Define a node class with integer data and a next pointer to the next node.
• Constructor to initialize the node with data.
2. Merge Two Sorted Lists:
• Create a dummy node with data 0 and l3 pointing to dummy.
• Iterate while both l1 and l2 are not null:
o Compare l1.data and l2.data.
o Connect the node with the smaller data to l3.
o Move the connected list (l1 or l2) to the next node.
o Move l3 to the connected node.
• If l1 is still remaining, connect the rest of l1 to l3.
• If l2 is still remaining, connect the rest of l2 to l3.
• Return the next node of the dummy.
3. Main Method:
• Create two sorted linked lists l1 and l2.
• Merge the two lists using the mergeTwoLists method and store the result
in dummy.
• Print the merged list data by iterating over dummy and traversing through the
nodes.
4. Output:
• Print the data of the merged linked list elements.
Code :
package LabQues;
class node
{
int data;
node next;
node(int data){
this.data = data;
}
Enrollment No : Page | 22
}
public class MergeTwoSortedList {
public static node mergeTwoLists(node l1, node l2) {
node dummy = new node(0);
node l3 = dummy;
while (l1 != null && l2 != null) {
if (l1.data < l2.data) {
l3.next = l1;
l1 = l1.next;
} else {
l3.next = l2;
l2 = l2.next;
}
l3 = l3.next;
}
if(l1 == null){
l3.next = l2;
}
else{
l3.next = l1;
}
return dummy.next;
}
public static void main(String[] args) {
node l1 = new node(1);
l1.next = new node(2);
l1.next.next = new node(4);
}
}
Enrollment No : Page | 23
Output :
Enrollment No : Page | 24
Practical 8
Aim : Write a Program to find the Merge point of two linked lists(sorted)
Algorithms :
This Java program defines a MergePointLinkedList class that contains a method findMergePoint
which takes two linked list nodes as input and finds the merge point (intersection node) of the
two linked lists.
1. Initialize two pointers, l1 and l2, pointing to the heads of the two linked lists.
2. Compare the data values of l1 and l2 nodes.
3. If l1.data is less than l2.data , move l1 to the next node.
4. If l1.data is greater than l2.data , move l2 to the next node.
5. If l1.data is equal to l2.data , it means the two linked lists intersect at this point, so return
• Two linked lists l1 and l2 are created with intersecting node intersectNode.
• The findMergePoint method is called with l1 and l2 as arguments to find the merge
point.
• If there is a merge point, it prints the data of the merge point node; otherwise, it prints
"No Merge Point found."
Code :
package LabQues;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
Enrollment No : Page | 25
public class MergePointLinkedList {
public static Node findMergePoint(Node l1, Node l2) {
while (l1 != l2) {
if (l1.data < l2.data) {
l1 = l1.next;
} else if (l1.data > l2.data) {
l2 = l2.next;
} else {
return l1;
}
}
return l1; // or return l2 (since they intersect at the same point)
}
if (mergePoint != null) {
System.out.println("Merge Point: " + mergePoint.data);
} else {
System.out.println("No Merge Point found.");
}
}
}
Output :
Enrollment No : Page | 26
Practical 9
Algorithms :
The code defines a Node class with integer data and a reference to the next node. It also includes
a SwapNodesInPairs class with two methods - swap for swapping data value of nodes in pairs
and addressSwap for swapping the nodes themselves in pairs.
1. swap(node head):
• Initialize a node l1 to the head of the list.
• Loop through the list as long as l1 and the next of l1 are not null.
• Swap the data values of l1 and l1.next.
• Move l1 two nodes ahead.
• Return the head of the list.
2. addressSwap(node head):
• Initialize l1 to the head and create a dummy node pointing to l1.
• Loop until there are at least two more nodes after point.
• Perform node swapping by adjusting the next references of nodes.
• Move point to the next pair of nodes.
• Return the modified list starting from the node after the dummy node.
3. main method:
• Create a linked list with nodes containing data 3, 5, 4, and 7.
• Call addressSwap method to swap nodes in pairs.
• Print the data of nodes in the modified list.
Here are the algorithms:
• swap(node head):
o Start from the head of the list.
o While there are at least two more nodes:
▪ Swap data values of current node and its next node.
▪ Move two nodes ahead.
o Return the head.
• addressSwap(node head):
o Start from the head and create a dummy node pointing to it.
o While there are at least two more nodes after point:
▪ Swap the next references of nodes to swap the nodes.
▪ Move to the next pair.
o Return the modified list starting from the node after the dummy.
• main method:
Enrollment No : Page | 27
o Create a linked list with data 3, 5, 4, and 7.
o Swap nodes in pairs.
o Print the modified list data.
Code :
package LabQues;
class node{
int data;
node next;
node(int data){
this.data = data;
}
}
public class SwapNodesInPairs {
Enrollment No : Page | 28
return dummy.next;
}
public static void main(String[] args){
node l1 = new node(3);
l1.next = new node(5);
l1.next.next = new node(4);
l1.next.next.next = new node(7);
node head = addressSwap(l1);
while(head != null){
System.out.print(head.data+" ");
head = head.next;
}
}
}
Output
Enrollment No : Page | 29
Practical 10
Aim : Write a Program to Understand and implement Tree traversals i.e. Pre-Order Post-
Order, In-Order
Algorithms :
• Pre-order traversal: Visit the root node, then recursively traverse the left subtree and
the right subtree.
• In-order traversal: Recursively traverse the left subtree, visit the root node, and then
recursively traverse the right subtree.
• Post-order traversal: Recursively traverse the left subtree, then the right subtree, and
finally visit the root node.
Code :
package LabQues;
public class TreeTraversals {
Node(int data) {
Enrollment No : Page | 30
this.data = data;
this.left = null;
this.right = null;
}
}
Enrollment No : Page | 31
// In-order traversal method
public static void inOrderTraversal(Node root) {
if (root == null) {
return;
}
inOrderTraversal(root.left); // Visit left subtree first
System.out.print(root.data + " "); // Then visit root
inOrderTraversal(root.right); // Then visit right subtree
}
Output :
Enrollment No : Page | 32
Practical 11
Algorithms :
1. Define a Node class representing a node in a binary tree. Each node contains data and
references to its left and right child nodes.
2. Implement a method areMirror(Node root1, Node root2) to recursively check if two
trees are mirror images of each other:
• If both trees are empty (both roots are null), return true.
• If one tree is empty and the other is not, return false.
• Check if the data in the current nodes match and their subtrees are mirror images
of each other by recursively calling areMirror on the left and right child nodes.
3. In the main method:
• Create two sample binary trees with mirrored structures.
• Check if the trees are mirror images by calling the areMirror method.
• Print whether the given trees are mirrored or not based on the result.
This algorithm recursively compares the data in corresponding nodes of two trees and checks if
their left and right subtrees are mirror images of each other to determine if the trees are mirrored.
Code :
package LabQues;
public class VerifyMirroredTrees {
Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
Enrollment No : Page | 33
// Method to check if two trees are mirror images
public static boolean areMirror(Node root1, Node root2) {
// Base case: Both trees are empty
if (root1 == null && root2 == null) {
return true;
}
// Main method for creating sample trees and checking if they are mirrored
public static void main(String[] args) {
// Create mirrored trees
Node root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
if (mirrored) {
System.out.println("Given trees are mirrored trees.");
} else {
System.out.println("Given trees are not mirrored trees.");
}
Enrollment No : Page | 34
}
}
Output :
Enrollment No : Page | 35
Practical 12
Algorithms :
This Java code defines a class named TreeDepth with a nested static class Node representing a
node in a binary tree. The maxDepth method calculates the maximum depth of the binary tree
using recursion.
Code :
package LabQues;
Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
Enrollment No : Page | 36
// Method to calculate the maximum depth of a tree
public static int maxDepth(Node root) {
if (root == null) {
return 0; // Empty tree has depth 0
}
// Main method for creating a sample tree and calculating its depth
public static void main(String[] args) {
// Create a sample binary tree
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);
Output :
Enrollment No : Page | 37
Practical 13
Aim : Write a program for Lowest Common Ancestors
Algorithm :
The algorithm implemented in the provided Java code for finding the Lowest Common
Ancestor (LCA) of two nodes in a binary tree is as follows:
1. Define a static nested class Node representing a node in a binary tree, with integer data,
left, and right child nodes.
2. Implement a findLCA method that takes the root of the tree and two node
values n1 and n2 as input:
• If the tree is empty or the root node matches either n1 or n2, return the current
root.
• Recursively search for n1 and n2 in the left and right subtrees.
• If both n1 and n2 are found in the left and right subtrees respectively, the current
root is the LCA.
• If only one node is found in either the left or right subtree, return that node.
3. In the main method:
• Create a sample binary tree with nodes and values.
• Find the LCA of nodes with values 4 and 7 in the tree by calling
the findLCA method.
• Print the data of the LCA node if found, else print "LCA not found."
This algorithm efficiently finds the Lowest Common Ancestor (LCA) of two nodes in a binary
tree by recursively searching for the nodes and determining the LCA based on their positions
in the tree.
Code :
package LabQues;
Node(int data) {
this.data = data;
Enrollment No : Page | 38
this.left = null;
this.right = null;
}
}
// If both left and right subtrees found a node, then root is LCA
if (leftLCA != null && rightLCA != null) {
return root;
}
// Return the only node found (if one is in left and the other in right)
return (leftLCA != null) ? leftLCA : rightLCA;
}
if (lca != null) {
Enrollment No : Page | 39
System.out.println("LCA of " + n1 + " and " + n2 + " is: " + lca.data);
} else {
System.out.println("LCA not found.");
}
}
}
Output :
Enrollment No : Page | 40
Practical 14
Aim : Write a Program to Build BST
Algorithm :
This Java code defines a Binary Search Tree (BST) class and a Solution class with methods to
insert nodes into the BST and perform an inorder traversal. Here are the algorithms in short:
1. BST Class:
• Data: An integer representing the data in the node.
• Left: A reference to the left child node in the BST.
• Right: A reference to the right child node in the BST.
2. Insert Method:
• Insert a new node with the given value val into the BST.
• If the root is null, create a new node with the value val.
• If the value is greater than the root's data, recursively insert into the right
subtree.
• If the value is less than or equal to the root's data, recursively insert into the left
subtree.
3. Inorder Traversal Method:
• Perform an inorder traversal of the BST (left subtree, root, right subtree).
• If the root is null, return.
• Recursively traverse the left subtree, then print the current node's data, and
finally recursively traverse the right subtree.
These algorithms work together to insert nodes into the BST in the correct order and print out
the data in sorted order using an inorder traversal.
Code :
package LabQues;
Enrollment No : Page | 41
}
class Solution{
public static void main(String[] args) {
BST root = null;
Output :
Enrollment No : Page | 42
Practical 16
Algorithms :
Code :
package LabQues;
import java.util.*;
Node(int data) {
this.data = data;
Enrollment No : Page | 43
this.left = null;
this.right = null;
}
}
while (!queue.isEmpty()) {
// Get the current node from the queue
Node current = queue.poll();
Enrollment No : Page | 44
root.left.right = new Node(5);
Output :
Enrollment No : Page | 45
Practical 18
Aim : Write a Program to view a tree from left View
Algorithms :
Code :
package LabQues;
Enrollment No : Page | 46
Node left, right;
Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
Enrollment No : Page | 47
Output :
Enrollment No : Page | 48