0% found this document useful (0 votes)
13 views42 pages

CC Lab Manual

The document is a lab manual for Utsav Chovatiya, a student at Parul Institute of Technology, detailing experiments in the Competitive Coding Laboratory for the 2nd Year, 4th Semester. It includes various programming tasks involving data structures such as stacks, queues, linked lists, trees, and hash functions, along with algorithms and example codes. Additionally, it certifies the completion of laboratory experiments during the academic year 2023-24.

Uploaded by

EDUNITI
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)
13 views42 pages

CC Lab Manual

The document is a lab manual for Utsav Chovatiya, a student at Parul Institute of Technology, detailing experiments in the Competitive Coding Laboratory for the 2nd Year, 4th Semester. It includes various programming tasks involving data structures such as stacks, queues, linked lists, trees, and hash functions, along with algorithms and example codes. Additionally, it certifies the completion of laboratory experiments during the academic year 2023-24.

Uploaded by

EDUNITI
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/ 42

PARUL INSTITUTE OFTECHNOLOGY

FACULTY OF ENGINEERING AND TECHNOLOGY


2303051050978

PARUL UNIVERISTY
PARUL INSTITUTE OF TECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY

Lab Manual
Name :- UTSAV CHOVATIYA

Enrollment no. :- 2303051050978

Roll no. :- 64

Division :- 4A-18

Subject :- Competitive Coding Laboratory

Year/Sem :- 2ndYear 4thSem

Faculty :- Dr. Pratik Gite


PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

CERTIFICATE
This is to certify that MAST. UTSAV CHOVATIYA with Enrollment no.

2303051050978 has successfully completed his laboratory experiments

in the Competitive Coding from the department of B. Tech

Computer Science & Engineering during academic year 2023-24.

Date of submission :- Staff in charge :-


PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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

2 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.
3 Write a program for finding NGE NEXT
GREATER ELEMENT from an array

4 Write a program to design a circular queue(k)


which Should implement the below functions
• Enqueue
• Dequeue
• Front
• Rear

5 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.
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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

7 Write a Program to Merge two linked


lists(sorted)
8 Write a Program to find the Merge point of
two linked lists(sorted)

9 Write a Program to Swap Nodes pairwise

10 Write a Program to Understand and


implement Tree traversals i.e. Pre-Order Post-
Order, In-Order
11 Write a Program to verify and validate
mirrored trees or not
12 Write a Program to determine the depth of a
given Tree by Implementing MAXDEPTH
13 Write a program for Lowest Common
Ancestors

14 Write a Program to Build BST


15 Write a Program for Building a Function
ISVALID to VALIDATE BST
16 Write a Program to Traverse a Tree using
Level Order Traversal
17 Write a Program to perform Boundary
Traversal on BST
18 Write a Program to view a tree from left View
19 Write a Program for a basic hash function in a
programming language of your choice.
Demonstrate its usage to store and retrieve
key-value pairs.
20 Write a Program to Implement Two sums
using HASHMAP
21 Write a Program to find Distinct substrings in
a string
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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.
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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;

public MinStack(int capacity) {


maxSize = capacity;
stack = new Stack<>();
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

minStack = new Stack<>();


}

public void push(int element) {


if (stack.size() >= maxSize) {
System.out.println("Overflow");
return;
}

stack.push(element);
if (minStack.isEmpty() || element <= minStack.peek()) {
minStack.push(element);
}
}

public void pop() {


if (stack.isEmpty()) {
System.out.println("Underflow");
return;
}

int popped = stack.pop();


if (popped == minStack.peek()) {
minStack.pop();
}
}

public int top() {


if (stack.isEmpty()) {
System.out.println("Stack is empty");
return -1;
}

return stack.peek();
}

public int getMin() {


if (minStack.isEmpty()) {
System.out.println("Stack is empty");
return -1;
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

return minStack.peek();
}

public void display() {


System.out.println("Elements in the stack:");
for (int i : stack) {
System.out.print(i + " ");
}
System.out.println();
}
}

public class Main {


public static void main(String[] args) {
MinStack minStack = new MinStack(5);
minStack.push(3);
minStack.push(5);
minStack.push(2);
minStack.push(7);
minStack.push(1);

minStack.display();

System.out.println("Min element in stack: " + minStack.getMin());

minStack.pop();
minStack.pop();

System.out.println("Top element in stack: " + minStack.top());


}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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.

2. Iterate through each character in the expression string:


• Check if the character is a digit:
• If yes, convert it to an integer using Character.getNumericValue and push it onto the
stack.
• Otherwise, the character is an operator (+, -, *, /):
• Pop two operands (operand1 and operand2) from the stack.
• Perform the operation indicated by the character on the two operands.
• Push the result back onto the stack.

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:

For the expression 36+9*, the algorithm works as follows:


• 3: Pushed onto the stack.
• 6: Pushed onto the stack.
•+: 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.
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Pop and return this element (324) as the result.

Code :

import java.util.Stack;

public class ExpressionEvaluation {


public static int evaluateExpression(String expression) {
Stack<Integer> stack = new 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();
}

public static void main(String[] args) {


String expression = "36+9*";
System.out.println("Result: " + evaluateExpression(expression));
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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.

1.Iterate through the input array in reverse order:


• For each element arr[i]:
• Pop elements from the stack until it's empty or the top element is greater than arr[i].
• If the stack becomes empty, it means there's no greater element to the right of arr[i], so
set result[i] to -1.
• Otherwise, the top element of the stack is the next greater element, so set result[i] to
stack.peek().
• Push arr[i] onto the stack.

3. Return the result array:


• The result array now contains the next greater elements for each element in the input
array.

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 :

import java.util.*;

public class NextGreaterElement {

public static int[] findNextGreaterElement(int[] arr) {


PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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


int n = arr.length;
int[] result = new int[n];

for (int i = n - 1; i >= 0; i--) {


while (!stack.isEmpty() && stack.peek() <= arr[i]) {
stack.pop();
}

if (stack.isEmpty()) {
result[i] = -1;
} else {
result[i] = stack.peek();
}

stack.push(arr[i]);
}

return result;
}

public static void main(String[] args) {


int[] arr = {4, 3, 2, 1, 5};
int[] nge = findNextGreaterElement(arr);

System.out.println("Next Greater Elements:");


for (int i : nge) {
System.out.print(i + " ");
}
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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)

3
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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 :

class Queue {
private int[] arr;
private int front;
private int size;
private int capacity;
public Queue(int c) {
arr = new int[c];
capacity = c;
size = 0;
front = 0;
}
public int getFront() {
if (size == 0)
return -1;
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

return arr[front];
}
public int getRear() {
if (size == 0)
return -1;
int rear = (front + size - 1) % capacity;
return arr[rear];
}
public void enqueue(int value) {
if (size == capacity) {
System.out.println("!...Queue is Full...!");
return;
}
int rear = (front + size) % capacity;
arr[rear] = value;
System.out.println(value+" get enqueued successfully.");
size++;
}
public int dequeue() {
if (size == 0)
return -1;
int res = arr[front];
front = (front + 1) % capacity;
size--;
System.out.println(res+" get dequeued successfully.");
return res;
}
}
class Cir_Queue {
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enqueue(10);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.enqueue(20);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.enqueue(30);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.enqueue(40);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.dequeue();
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.dequeue();
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.enqueue(50);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.enqueue(60);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.enqueue(70);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
queue.enqueue(80);
System.out.println("Front: "+queue.getFront() + " " + "Rear: "+queue.getRear());
}
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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 :

import java.util.*;
public class InfixToPostfix {
public static String infixToPostfix(String infix) {String postfix = "";
Stack<Character> operatorStack = new Stack<>();
HashMap<Character, Integer> precedence = new HashMap<>();
precedence.put('+', 1);
precedence.put('-', 1);
precedence.put('*', 2);
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

precedence.put('/', 2);
precedence.put('^', 3);
for (char c : infix.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
postfix += c;
} else if (c == '(') {
operatorStack.push(c);
} else if (c == ')') {
while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {
postfix += operatorStack.pop();
}
operatorStack.pop(); // Pop '('
} else {
while (!operatorStack.isEmpty() && precedence.getOrDefault(c, 0) <=
precedence.getOrDefault(operatorStack.peek(), 0)) {
postfix += operatorStack.pop();
}
operatorStack.push(c);
}
}
while (!operatorStack.isEmpty()) {
postfix += operatorStack.pop();
}
return postfix;
}

public static void main(String[] args) {


String infixExpression = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println("Postfix expression: " + infixToPostfix(infixExpression));
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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 :

1. Initialize Priority Queue:


• Create a Priority Queue pq with a custom comparator to keep

the elements in descending order.


2. Insert Elements:
• Iterate over the input array nums.

• Add each element to the priority queue using the offer method.

3. Find Three Largest Elements:


• Retrieve the three largest elements from the priority

queue by using the poll method three times.


• Store them in variables largest1, largest2, and largest3.
4. Calculate Product:
• Compute the product of the three largest elements obtained.

• Multiply largest1, largest2, and largest3.

• Return the result as the product of the three largest distinct elements.

5. Main Method Execution:


• Create an array nums with integers {5, 10, 2, 8, 15, 3}.

• Call the findProductOfThreeLargest method with nums array as input.

• Display the product of the three largest distinct elements to the console.
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Code :

import java.util.*;
public class ThreeLargestProduct {

public static int findProductOfThreeLargest(int[] nums) {


PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

for (int num : nums) {


pq.offer(num);
}

int largest1 = pq.poll();

int largest2 = pq.poll();


int largest3 = pq.poll();

return largest1 * largest2 * largest3;


}

public static void main(String[] args) {


int[] nums = {5, 10, 2, 8, 15, 3};
System.out.println("Product of the three largest distinct elements: " +
findProductOfThreeLargest(nums));
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Practical 7

Aim : Write a Program to Merge two linked lists(sorted)

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 :
import java.util.*;
class node{
int data;
node next;
node(int data){
this.data = data;
}
}
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) {
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

}
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);
node l2 = new node(1);
l2.next = new node(3);
l2.next.next = new node(4);
node dummy = mergeTwoLists(l1, l2);
while(dummy != null){
System.out.print(dummy.data + " ");
dummy = dummy.next;
}

}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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.

Here's a breakdown of the algorithm implemented:

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

the intersecting node.


6. Repeat steps 2-5 until l1 is equal to l2 (i.e., they point to the same node).
7. Return the node at which the two linked lists merge.
In the main method:

• 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 :
import java.util.*;

class Node {
int data;
Node next;

Node(int data) {
this.data = data;
}
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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

public static void main(String[] args) {


Node intersectNode = new Node(8);

Node l1 = new Node(1);


l1.next = new Node(3);
l1.next.next = new Node(5);
l1.next.next.next = intersectNode;

Node l2 = new Node(2);


l2.next = new Node(4);
l2.next.next = intersectNode;

Node mergePoint = findMergePoint(l1, l2);

if (mergePoint != null) {
System.out.println("Merge Point: " + mergePoint.data);
} else {
System.out.println("No Merge Point found.");
}
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Practical 9

Aim : Write a Program to Swap Nodes pairwise

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:
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

o Create a linked list with data 3, 5, 4, and 7.


o Swap nodes in pairs.
o Print the modified list data.

Code :
import java.util.*;

class node{
int data;
node next;
node(int data){
this.data = data;
}
}
public class SwapNodesInPairs {
public static node swap(node head){
node l1 = head;
while (l1 != null && l1.next != null){
int temp = l1.data;
l1.data = l1.next.data;
l1.next.data = temp;
l1 = l1.next.next;
}
return head;
}
public static node addressSwap(node head){
node l1 = head;
node dummy = new node(-1);
dummy.next = l1;
node point = dummy;
while(point.next != null && point.next.next != null){
node swap1 = point.next;
node swap2 = point.next.next;
swap1.next = swap2.next;
swap2.next = swap1;
point.next = swap2;
point = swap1;
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Practical 10
Aim : Write a Program to Understand and implement Tree traversals i.e. Pre-Order Post-
Order, In-Order

Algorithms :

• The code defines a class TreeTraversals inside the package LabQues.


• Inside the class, there is a static nested class Node representing a node in a binary tree.
• The Node class has fields for data, left child, and right child.
• The code creates sample binary tree with 5 nodes numbered from 1 to 5.
• The code then performs three types of tree traversals: Pre-order, In-order, and Post-
order.
• Pre-order traversal visits the root node first, then the left subtree, and finally the right
subtree.
• In-order traversal visits the left subtree first, then the root node, and finally the right
subtree.
• Post-order traversal visits the left subtree first, then the right subtree, and finally the
root node.
Here are the 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 :
import java.util.*;

public class TreeTraversals {

static class Node {


int data;
Node left, right;

Node(int data) {

this.data = data;

this.left = null;
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

this.right = null;

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

// Pre-order traversal
System.out.print("Pre-order traversal: ");
preOrderTraversal(root);
System.out.println();

// In-order traversal
System.out.print("In-order traversal: ");
inOrderTraversal(root);
System.out.println();

// Post-order traversal
System.out.print("Post-order traversal: ");
postOrderTraversal(root);
System.out.println();
}

public static void preOrderTraversal(Node root) {


if (root == null) {
return;
}
System.out.print(root.data + " ");
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

public static void inOrderTraversal(Node root) {


if (root == null) {
return;
}
inOrderTraversal(root.left);
System.out.print(root.data + " ");
inOrderTraversal(root.right);
}

public static void postOrderTraversal(Node root) {


if (root == null) {
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.print(root.data + " ");
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Practical 11

Aim : Write a Program to verify and validate mirrored trees or not

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 :
import java.util.*;
public class VerifyMirroredTrees {

static class Node {


int data;
Node left, right;

Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

public static boolean areMirror(Node root1, Node root2) {


if (root1 == null && root2 == null) {
return true;
}
if (root1 == null || root2 == null) {
return false;
}

return root1.data == root2.data &&


areMirror(root1.left, root2.right) &&
areMirror(root1.right, root2.left);
}

public static void main(String[] args) {


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

Node root2 = new Node(1);


root2.left = new Node(3);
root2.right = new Node(2);
root2.right.left = new Node(5);
root2.right.right = new Node(4);
boolean mirrored = areMirror(root1, root2);

if (mirrored) {
System.out.println("Given trees are mirrored trees.");
} else {
System.out.println("Given trees are not mirrored trees.");
}

}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Practical 12

Aim : Write a Program to determine the depth of a given Tree by Implementing


MAXDEPTH

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.

1. The maxDepth method takes a Node as input.


2. If the input node is null, it returns 0 (indicating an empty tree).
3. It recursively calculates the depths of the left and right subtrees by calling maxDepth on
the left and right child nodes.
4. It then returns the larger depth of the left and right subtrees plus 1 (for the current node).
5. The main method creates a sample binary tree with nodes and calculates the depth of
the tree using the maxDepth method.
In short, the algorithm recursively calculates the depth of a binary tree by finding the maximum
depth of its left and right subtrees and adding 1 for the current node.

Code :
import java.util.*;

public class TreeDepth {

static class Node {


int data;
Node left, right;

Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}

public static int maxDepth(Node root) {


if (root == null) {
return 0; // Empty tree has depth 0
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

return Math.max(leftDepth, rightDepth) + 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);

int depth = maxDepth(root);


System.out.println("Depth of the tree: " + depth);
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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 :

import java.util.*;

public class LowestCommonAncestor {


static class Node {
int data;
Node left, right;

Node(int data) {
this.data = data;
this.left = null;
this.right =null;
}
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

public static Node findLCA(Node root, int n1, int n2) {


// Base case: Empty tree or root matches one of the nodes
if (root == null || root.data == n1 || root.data == n2) {
return root;
}
Node leftLCA = findLCA(root.left, n1, n2);
Node rightLCA = findLCA(root.right, n1, n2);
if (leftLCA != null && rightLCA != null) {
return root;
}
return (leftLCA != null) ? leftLCA : rightLCA;
}
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);
root.right.left = new Node(6);
root.right.right = new Node(7);
int n1 = 4, n2 = 7;
Node lca = findLCA(root, n1, n2);

if (lca != null) {

System.out.println("LCA of " + n1 + " and " + n2 + " is: " + lca.data);


} else {
System.out.println("LCA not found.");
}
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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 :

import java.util.*;

public class BST {


int data;
BST left;
BST right;

public BST(int data){


this.data= data;
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

}
class Solution{
public static void main(String[] args) {
BST root = null;

root = insert(root, 80);


insert(root, 60);
insert(root, 90);
insert(root, 10);
insert(root, 70);
insert(root, 85);
insert(root, 110);
inorder(root);
}
public static BST insert(BST root, int val){
if(root == null){
return new BST(val);
}
if(root.data < val){
root.right = insert(root.right, val);
}
else{
root.left = insert(root.left, val);
}
return root;
}
public static void inorder(BST root){
if(root == null){
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Practical 16

Aim : Write a Program to Traverse a Tree using Level Order Traversal

Algorithms :

1. Node Class Definition:


• Define a static nested class Node representing a node in a binary tree, with data,
left child, and right child attributes.
• Initialize the Node with the data provided and set left and right child to null
initially.
2. Level Order Traversal Method (levelOrderTraversal):
• Accepts the root node of the binary tree as input.
• If the root is null, return.
• Create a queue (LinkedList) to store nodes.
• Add the root node to the queue.
• While the queue is not empty:
o Dequeue the current node from the queue.
o Print the data of the current node.
o Enqueue the left and right children of the current node if they exist.
3. Main Method:
• Create a sample binary tree with nodes and connections.
• Call the levelOrderTraversal method with the root of the binary tree.
• Print the output of the level order traversal.

Code :

import java.util.*;

public class LevelOrderTraversal {


static class Node {
int data;
Node left, right;

Node(int data) {
this.data = data;
this.left = null;
this.right =null;
}
}
public static void levelOrderTraversal(Node root) {
if (root == null) {
return;
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

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


queue.add(root);

while (!queue.isEmpty()) {
Node current = queue.poll();
System.out.print(current.data + " ");
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
}
}
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);

// Perform Level Order Traversal


System.out.print("Level Order Traversal: ");
levelOrderTraversal(root);
System.out.println();
}
}

Output :
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

Practical 15
Aim : Write a Program for Building a Function ISVALID

to VALIDATE BST Algorithms :

1. Node Class Definition:


• Define a static nested class Node representing a node in a binary tree, with data,
left child, and right child attributes.
• Initialize the node with the provided data and set left and right children to null
initially.
2. Is Valid BST Function (isValidBST):
• Accepts the current node, minimum value, and a maximum value visited so far
as inputs.
• If the current node is null, return true.
• Compare the current node value with the maximum and minimum value:
o If the current node value is greater then maximum value or, current
node value is less then minimum value then return false.
• Recursively call the function for the left and right subtrees with node value as
minimum value in case of right subtree and maximum value in case of left
subtree.
• Return if both are true else false.
3. Is Valid Function:
• Accepts the root node of the binary tree as input.
• Call the isValidBST function recursively and passing the root node, the min.
value and the max. value as argument .
4. Main Method:
• Create a sample binary tree with nodes and connections.
• Call the isValidBST function with the root of the binary tree.
• Print the output as the Validation of the binary tree.

Code :

import java.util.*;

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
PARUL INSTITUTE OFTECHNOLOGY
FACULTY OF ENGINEERING AND TECHNOLOGY
2303051050978

public class Solution {


public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean isValidBST(TreeNode node, long minVal, long maxVal) {
if (node == null) {
return true;
}
if (node.val <= minVal || node.val >= maxVal) {
return false;
}
return isValidBST(node.left, minVal, node.val) && isValidBST(node.right, node.val, maxVal);
}

public static void main(String[] args) {


TreeNode root = new TreeNode(4);
root.left = new TreeNode(2);
root.right = new TreeNode(5);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(3);

Solution solution = new Solution();


boolean result = solution.isValidBST(root);
System.out.println("The given tree is valid BST? ==> "+result);
}
}

You might also like