0% found this document useful (0 votes)
2 views76 pages

ADSA Lab

The document outlines a lab course for Bachelor of Engineering & Technology students at Galgotias University, focusing on advanced data structures and algorithms. It includes various programming experiments, each detailing the aim, description, source code, and expected output for tasks such as reversing strings, finding the Kth largest element, and managing linked lists. The document serves as a practical guide for students to implement and understand key algorithms and data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views76 pages

ADSA Lab

The document outlines a lab course for Bachelor of Engineering & Technology students at Galgotias University, focusing on advanced data structures and algorithms. It includes various programming experiments, each detailing the aim, description, source code, and expected output for tasks such as reversing strings, finding the Kth largest element, and managing linked lists. The document serves as a practical guide for students to implement and understand key algorithms and data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Advance Data Structure & Algorithm

Course Code: R1UC503B

Lab
File
For
BACHELOR OF

ENGINEERING &

TECHNOLOGY

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

GALGOTIAS UNIVERSITY, GREATER NOIDA

UTTAR PRADESH

Student Name: ROHIT GUPTA

Admission No:

22SCSE1010530 Semester : V

1|Page
EXPERIMENT NO. :22131010830

PROGRAM :

1.DESCRIPTION (INTRODUCTION)
2.SOURCE CODE (TYPED)

3.OUTPUT (PASTE SCREEN-SHOT)

2|Page
EXPERIMENT NO. :01

AIM : To Reverse the String

PROGRAM :

1.DESCRIPTION

Reverse the string is a common problem where the goal is to


reverse the order of characters in a given string. For
example, given the input string "hello", the output should be
"olleh". This can be achieved using
various methods, such as iterating over the string from both
ends and swapping characters, using a stack to reverse the
order, or utilizing built- in string manipulation functions in
programming languages. The problem is often used to practice
basic string manipulation and algorithmic thinking

2.SOURCE CODE (TYPED)


class Solution {
public void reverseString(char[]
s) { int front=0;
int back=s.length-
1;
while(front<bac
k){
char
temp=s[front];
s[front]=s[back]
;
s[back]=temp;
front++;
3|Page
back--;
}

4|Page
}
}
3.OUTPUT (PASTE SCREEN-SHOT)

5|Page
EXPERIMENT NO. :02

AIM . Kth Largest Element in an Array

PROGRAM :

1.DESCRIPTION

The Kth largest element in an array is the element that would appear
in the
Kth position if the array were sorted in descending order. It can
be found by sorting the array or using more efficient methods
like a min-heap or the Quickselect algorithm.

2.SOURCE CODE (TYPED)


class Solution {
public int findKthLargest(int[] nums, int k)
{ PriorityQueue<Integer> pq=new
PriorityQueue<>(Collections.reverseOrder())
; for(int i:nums) pq.add(i);
for(int i=1;i<k;i++) pq.remove();
return pq.peek();
}
}

3.OUTPUT (PASTE SCREEN-SHOT)

6|Page
EXPERIMENT NO. :03

AIM : Sort Colors

PROGRAM :

1.DESCRIPTION (INTRODUCTION)

The Sort Colors problem involves sorting an array of integers


where each element is either 0, 1, or 2. The goal is to sort
the array so that all 0's come first, followed by all 1's, and
then all 2's, in linear time and constant space. A common
approach is the Dutch National Flag algorithm, which uses
three pointers to efficiently partition the array into these
three sections
2.SOURCE CODE (TYPED)
class Solution {
public void sortColors(int[]
nums) { int n=nums.length;
int c0=0,c1=0,c2=0;
for(int i=0;i<n;i++)
{
if(nums[i]==0) c0++;
else if(nums[i]==1)
c1++; else c2++;
}
for(int i=0;i<n;i++)
{ if(c0!=0){
nums[i]=0;
c0--;
}
else if(c1!
=0){
nums[i]=
1; c1--;
7|Page
}
else{
nums[i]=
2; c2--;
}
}
}
}
3.OUTPUT (PASTE SCREEN-SHOT)

8|Page
EXPERIMENT NO. :04
AIM : To move zeros

PROGRAM :

1.DESCRIPTION (INTRODUCTION)
The Move Zeroes program involves shifting all zero elements in
an array to the end while maintaining the relative order of non-
zero elements. This can be done efficiently in linear time (O(n))
by iterating through the array and swapping non-zero
elements with zero elements.

2.SOURCE CODE (TYPED)


class Solution {
public void moveZeroes(int[]
nums) { int i=0;
int count=0;
for(int j=0;j<nums.length;j++)
{
if(nums[j]!=0)
{
nums[i]=nums[j];
i++;
}
if(nums[j]==0)
{}
count++;

}
for( int k=0;k<count;k++)
{
nums[i]=0; i+
+;

9|Page
}
}
}

3.OUTPUT (PASTE SCREEN-SHOT)

10 | P a g
e
EXPERIMENT NO. :05
AIM : To reverse

PROGRAM :

1.DESCRIPTION

The Reverse Array program reverses the elements of an array in


place. It
can be done by swapping the elements at the beginning and
end of the array, then moving towards the center, ensuring that
the array is reversed with a time complexity of O(n).

2.SOURCE CODE
class Solution {
public ListNode reverseList(ListNode head) {

ListNode prev=null;
ListNode curr=head;
while(curr!=null){
ListNode nxt=curr.next;
curr.next=prev;
prev=curr;
curr=nxt;
}
return prev;
}
11 | P a g
e
}

3.OUTPUT (PASTE SCREEN-SHOT)

12 | P a g
e
EXPERIMENT NO. :7

AIM : Linked List Cycle II

PROGRAM :

1.DESCRIPTION

The Linked List Cycle II program detects the start of a cycle in a linked
list. Using Floyd’s Tortoise and Hare algorithm, two pointers are
moved at different speeds. If a cycle exists, they meet at
some point; then, one pointer is moved to the head and both
pointers move at the same pace to find the cycle's starting
node.

2.SOURCE CODE
public class Solution { public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next !=
null){ slow = slow.next;
fast = fast.next.next;
if (slow == fast) break;
}
if (fast == null || fast.next == null) return null;
while (head != slow) {
head = head.next;
slow =
slow.next;
}
return head;

13 | P a g
e
}
}
3.OUTPUT (PASTE SCREEN-SHOT)

14 | P a g
e
EXPERIMENT NO. :8
AIM : middle of the linked list II

PROGRAM :

1.DESCRIPTION

The Middle of the Linked List II program finds the middle node of a
linked list. Using the slow and fast pointer technique, the slow
pointer moves one step at a time, while the fast pointer moves
two steps. When the fast pointer reaches the end, the slow
pointer will be at the middle node.
2.SOURCE CODE
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast =
fast.next.next;
}
return slow;
}
}

15 | P a g
e
3.OUTPUT (PASTE SCREEN-SHOT)

16 | P a g
e
EXPERIMENT NO. :9
AIM : merge two sorted list

PROGRAM :

1.DESCRIPTION

The Merge Two Sorted Lists program merges two sorted linked lists
into a
single sorted linked list. It iterates through both lists,
comparing their nodes and appending the smaller node to the
result list, until all nodes from both lists are merged.

2.SOURCE CODE (TYPED)


class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {

if(list1!=null && list2!=null){


if(list1.val<list2.val){
list1.next=mergeTwoLists(list1.next,list2);
return list1;
}
else{
list2.next=mergeTwoLists(list1,list2.next);
return list2;
}
}
if(list1==null)
return
list2;
return
list1;
}
}
17 | P a g
e
3.OUTPUT (PASTE SCREEN-SHOT)

18 | P a g
e
EXPERIMENT NO. :10
AIM : Remove Nth Node From End of List

PROGRAM :

1.DESCRIPTION

The Remove Nth Node from End of List program removes the Nth node
from the end of a linked list. It uses two pointers: one moves N
steps ahead, then both pointers move together until the first
pointer reaches the end, allowing the second pointer to point
to the node before the Nth from the end, which can then be
removed.

2.SOURCE CODE
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head, slow = head;
for (int i = 0; i < n; i++) fast =
fast.next; if (fast == null) return
head.next; while (fast.next !=
null) {
fast = fast.next;
slow =
slow.next;
}
slow.next = slow.next.next;
return head;
}
}

19 | P a g
e
3.OUTPUT (PASTE SCREEN-SHOT)

19 | P a g e
EXPERIMENT NO. :11

AIM : Design a Stack With Increment Operation

PROGRAM :

1.DESCRIPTION

The Design a Stack with Increment Operation program implements a


stack
that supports the standard push and pop operations, along
with an additional increment(k, val) operation. This
operation adds a value val to the bottom k elements of
the stack. The goal is to efficiently handle these
operations.

2.SOURCE CODE
class CustomStack {
private:
vector<int>
stack; int
maxSize;

public:
CustomStack(int maxSize) :
maxSize(maxSize) {} void push(int x) {
if (stack.size() < maxSize) {
stack.push_back(x);
}
}

int pop() {
if (stack.empty())
{ return -1;
20 | P a g
e
}
int top =
stack.back();
stack.pop_back();
return top;
}
void increment(int k, int val) {
int limit = min(k,
(int)stack.size()); for (int i = 0;
i < limit; ++i) {
stack[i] += val;
}
}
};

3.OUTPUT (PASTE SCREEN-SHOT)

21 | P a g
e
EXPERIMENT NO. :12
AIM : Min Stack

PROGRAM :

1.DESCRIPTION

The Min Stack program implements a stack that supports the


standard push, pop, and top operations, along with a
getMin() operation that returns the minimum element in the
stack in constant time. It uses an auxiliary stack to keep
track of the minimum values.

2.SOURCE CODE
class MinStack {
private:
stack<int>
mainStack;
stack<int>
minStack;
public:

MinStack() {}

void push(int val) {


mainStack.push(val);
if (minStack.empty() || val <= minStack.top()) {
minStack.push(val);
}
}
void pop() {

22 | P a g
e
if (!mainStack.empty()) {

23 | P a g
e
if (mainStack.top() == minStack.top()) {
minStack.pop();
}
mainStack.pop();
}
}

int top() {
return mainStack.top();
}

int getMin() {
return minStack.top();
}
};

3.OUTPUT (PASTE SCREEN-SHOT)

24 | P a g
e
EXPERIMENT NO. :13
AIM Valid Parentheses

PROGRAM :

1.DESCRIPTION (INTRODUCTION)

The Valid Parentheses program checks if a string of parentheses is


valid. It
uses a stack to ensure that each opening parenthesis has a
corresponding closing parenthesis in the correct order. The
string is valid if the stack is empty at the end of the process.

2.SOURCE CODE (TYPED)


class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for (char ch : s)
{
if (ch == '(' || ch == '{' || ch == '[')
{ stk.push(ch);
} else {
if (stk.empty())
{ return
false;
}
char top = stk.top();
if ((ch == ')' && top == '(') ||
(ch == '}' && top == '{') ||
(ch == ']' && top == '[')) {
stk.pop();
} else {
25 | P a g
e
return false;

26 | P a g
e
}
}
}
return stk.empty();

}
};

3.OUTPUT

27 | P a g
e
EXPERIMENT NO. :14

AIM : Next Greater Element I

PROGRAM :

1.DESCRIPTION

The Next Greater Element I program finds the next greater element for
each element in a given array, relative to a second array. It uses a
stack to efficiently track the next greater elements for each
value, providing an optimal solution in linear time.

2.SOURCE CODE
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1,
vector<int>& nums2) {
unordered_map<int, int> nextGreaterMap; // Map to store the
next greater element for each number in nums2.
stack<int> stk;
for (int i = nums2.size() - 1; i >= 0; --i) {
int num = nums2[i];
while (!stk.empty() && stk.top() <= num) {
stk.pop();
}
nextGreaterMap[num] = stk.empty() ? -1 :
stk.top(); stk.push(num);
}

28 | P a g
e
vector<int> result;
for (int num : nums1) {
result.push_back(nextGreaterMap[num]);
}
return result;

}
};
3.OUTPUT

29 | P a g
e
EXPERIMENT NO. :15
AIM Next Greater Element I

PROGRAM :

1.DESCRIPTION

The Next Greater Element II program finds the next greater element
for
each element in a circular array. It uses a stack to track
elements and ensures that after reaching the end of the array,
it wraps around to check for the next greater element in the
beginning.

2.SOURCE CODE
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1,
vector<int>& nums2) {
unordered_map<int, int> nextGreaterMap;
stack<int> stk;

for (int i = nums2.size() - 1; i >= 0;


--i) { int num = nums2[i];
while (!stk.empty() && stk.top() <= num) {
stk.pop();
}
nextGreaterMap[num] = stk.empty() ? -1 :
stk.top(); stk.push(num);
}
vector<int> result;

30 | P a g
e
for (int num : nums1) {
result.push_back(nextGreaterMap[num]);
}
return result;
}
};

3.OUTPUT

31 | P a g
e
EXPERIMENT NO. :16
AIM : Design Circular Queue

PROGRAM :

1.DESCRIPTION

The Design Circular Queue program implements a circular queue with


fixed size, where the front and rear pointers wrap around when
they reach the end. It supports operations like enqueue,
dequeue, front, and rear, ensuring efficient use of space by
reusing empty spots.

2.SOURCE CODE
class MyCircularQueue {
private:
vector<int> queue;
int head;
int tail;
int capacity;
int size;

public:

MyCircularQueue(int k) : queue(k), head(0), tail(-1), capacity(k), size(0)


{}

bool enQueue(int
value) { if (isFull())
{
return false;
}
tail = (tail + 1) % capacity;

32 | P a g
e
queue[tail] =
value; size++;
return true;
}
bool deQueue() {
if (isEmpty())
{ return
false;
}
head = (head + 1) %
capacity; size--;
return true;
}
int Front() {
if (isEmpty()) {
return -1;
}
return queue[head];
}
int Rear() {
if (isEmpty()) {
return -1;
}
return queue[tail];
}
bool isEmpty() {
return size == 0;
}

bool isFull() {
return size == capacity;
}
};

33 | P a g
e
3.OUTPUT

34 | P a g
e
EXPERIMENT NO. :17
AIM : Implement Queue using Stacks

PROGRAM :

1.DESCRIPTION

The Implement Queue using Stacks program simulates a queue using


two
stacks. It supports enqueue and dequeue operations by using one
stack for input and another for output, ensuring that elements
are processed in the correct order (FIFO).

2.SOURCE CODE
class MyQueue {
Stack<Integer> stack1 = new
Stack<>(); Stack<Integer> stack2 =
new Stack<>(); public MyQueue()
{

public void push(int x) {


for( ; !stack1.isEmpty(); ){
stack2.push(stack1.pop());
}
stack1.push(x);
for(; !stack2.isEmpty(); ){
stack1.push(stack2.pop());
}
}
33 | P a g e
public int pop() {
return
stack1.pop();
}
public int peek() {
return stack1.peek();
}

public boolean
empty() {
if(stack1.isEmpty(
)){ return true;
}
return false;
}
}

3.OUTPUT

34 | P a g
e
EXPERIMENT NO. :18
AIM : Implement Stack using Queues

PROGRAM :

1.DESCRIPTION

The Implement Stack using Queues program simulates a stack using


two
queues. It supports push and pop operations by manipulating the
queues to maintain the Last-In-First-Out (LIFO) order of
elements.
2.
3.SOURCE CODE (TYPED)
class MyStack {

Queue<Integer> q1;
Queue<Integer> q2;
int top;

public MyStack() {
q1 = new LinkedList<>();
q2 = new
LinkedList<>();
}
public void push(int x) {
top = x;
if(q1.isEmpty() && q2.isEmpty()){
q1.offer(x);
} else if (q1.isEmpty()){
q2.offer(x);
} else if (q2.isEmpty()){
35 | P a g
e
q1.offer(x);

36 | P a g
e
}
}
public int pop() {
if(q1.isEmpty() &&
q2.isEmpty()){ return 0;
} else if (q1.isEmpty()){
return getTopFromQueue(q2, q1);
} else if (q2.isEmpty()){
return getTopFromQueue(q1, q2);
}
return 0;
}
private int getTopFromQueue(Queue<Integer> data,
Queue<Integer>
aux){
var size = data.size();

for(int i = 0; i < size -1; i+


+){ top = data.poll();
aux.offer(top);
}
return data.poll();
}
public int top() {
return top;
}

public boolean empty() {


if (q1.isEmpty() && q2.isEmpty())
return true;

return false;
}
}

37 | P a g
e
4.OUTPUT

38 | P a g
e
EXPERIMENT NO. :19

AIM : Insert into a binary search tree

PROGRAM :

1.DESCRIPTION

The Insert into a Binary Search Tree program inserts a new


node into a binary search tree (BST) while maintaining its
properties. It starts at the root, compares the new value, and
recursively inserts it to the left or right subtree based on the
comparison.

2.SOURCE CODE
class Solution {
public TreeNode insertIntoBST(TreeNode root, int
val) { if(root == null) {
root = new TreeNode(val);
return root;
}
if(val < root.val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}

38 | P a g e
3.OUTPUT

39 | P a g e
EXPERIMENT NO. :20

AIM : Search in a Binary Search Tree


PROGRAM :

1.DESCRIPTION

The Search in a Binary Search Tree program searches for a target


value in
a binary search tree (BST). It starts at the root and recursively
traverses the left or right subtree based on whether the target
is smaller or larger than the current node, ensuring an efficient
search.

2.SOURCE CODE
class Solution {
public TreeNode searchBST(TreeNode root, int
val) { if(root == null){
return null;
}
if(root.val == val) return root;

if(val<root.val){
return searchBST(root.left , val);
}
else{
return searchBST(root.right , val);
}

}
}
40 | P a g e
3.OUTPUT

41 | P a g e
EXPERIMENT NO. :21

AIM Binary Tree Preorder Traversal


PROGRAM :

1.DESCRIPTION

The Binary Tree Preorder Traversal program traverses a binary tree


in
preorder (root, left, right). It visits the root node first, then
recursively traverses the left subtree, followed by the right
subtree. This can be implemented using recursion or a stack.

2.SOURCE CODE
class Solution {
LinkedList<Integer> res = new LinkedList<>();

public List<Integer> preorderTraversal(TreeNode root) {


preOrder(root);
return res;
}
public void preOrder(TreeNode root) {
if (root == null) {
return;
}
res.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
}

42 | P a g e
3.OUTPUT

43 | P a g
e
EXPERIMENT NO. :22
AIM Binary Tree Inorder Traversal

PROGRAM :

1.DESCRIPTION

The Binary Tree Inorder Traversal program traverses a binary tree in


inorder (left, root, right). It recursively visits the left subtree, then the
root node, and finally the right subtree, ensuring nodes are
processed in ascending order for a BST.

2.SOURCE CODE
class Solution {
public List<Integer> inorderTraversal(TreeNode
root) { List<Integer> list = new ArrayList<>();
inorderRec(root,list);
return list;
}
private void inorderRec(TreeNode root, List<Integer> list)
{
if(root != null)
{ inorderRec(root.left,list);
list.add(root.val);
inorderRec(root.right,list);
}
}
}

44 | P a g
e
3.OUTPUT

45 | P a g
e
EXPERIMENT NO. :23
AIM : Binary Tree Postorder Traversal

PROGRAM :

1.DESCRIPTION

The Binary Tree Postorder Traversal program traverses a binary tree


in
postorder (left, right, root). It recursively visits the left and right
subtrees before processing the root node. This traversal is
useful for tasks like deleting nodes or evaluating expressions.

2.SOURCE CODE
class Solution {
public List<Integer> postorderTraversal(TreeNode
root) { List<Integer> result = new ArrayList<>();
postOrder(root, result);
return result;
}

private void postOrder(TreeNode node, List<Integer>


result) { if (node == null) {
return;
}
postOrder(node.left, result); // Traverse the left subtree
postOrder(node.right, result); // Traverse the right subtree
result.add(node.val); // Add the root node's value after the
children
}
}

46 | P a g
e
3.OUTPUT (PASTE SCREEN-SHOT)

47 | P a g
e
EXPERIMENT NO. :24
AIM Binary Tree Level Order Traversal

PROGRAM :

1.DESCRIPTION

The Binary Tree Level Order Traversal program traverses a binary tree
level by level, from top to bottom and left to right. It uses a
queue to process nodes at each level in sequence, ensuring that
all nodes at a given level are visited before moving to the
next.

2.SOURCE CODE
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>(); // Final result
list
if (root == null) {
return result; // If the root is null, return an empty list
}

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


queue.add(root); // Start with the root in the
queue while (!queue.isEmpty()) {
int levelSize = queue.size(); // Number of nodes at the current
level List<Integer> currentLevel = new ArrayList<>(); // List to
hold
values of nodes at this level

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


48 | P a g e
TreeNode currentNode = queue.poll(); // Get the next
queu node in the currentLevel.add(currentNode.val); // Add the
e node's value to the

current level's list

// Add the children of the current node to the queue, if


they exist if (currentNode.left != null) {
queue.add(currentNode.left);
}
if (currentNode.right != null) {
queue.add(currentNode.right);
}
}
result.add(currentLevel); // Add the current level's list to the final
result list
}

return result;
}
}

3.OUTPUT

49 | P a g
e
EXPERIMENT NO. :25
AIM : Maximum Depth of Binary

PROGRAM :

1.DESCRIPTION

The Maximum Depth of Binary Tree program calculates the longest


path
from the root to any leaf node. It recursively computes the depth of
the left and right subtrees, returning the greater depth plus one.

2.SOURCE CODE
class Solution {
public int maxDepth(TreeNode
root) { if (root == null) {
return 0; // If the tree is empty, the depth is 0
}
// Recursively find the depth of the left and right
subtrees int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);

return Math.max(leftDepth, rightDepth) + 1;


}
}

50 | P a g
e
3.OUTPUT (PASTE SCREEN-SHOT)

51 | P a g
e
EXPERIMENT NO. :26
AIM : Diameter of Binary Tree

PROGRAM :
1. DESCRIPTION (INTRODUCTION)
The Diameter of Binary Tree program calculates the longest path
between
any two nodes in a binary tree. It finds the maximum distance
by considering the depth of left and right subtrees for each node,
recursively updating the diameter.

2. SOURCE CODE (TYPED)

class Solution {
private int maxDiameter = 0; // To store the maximum
diameter public int diameterOfBinaryTree(TreeNode
root) {
calculateDepth(root); // Start recursive depth
calculation return maxDiameter; // Return the
maximum diameter found
}
private int calculateDepth(TreeNode node) {
if (node == null) {
return 0; // Base case: depth of a null node is 0
}
int leftDepth =
calculateDepth(node.left); int
rightDepth =
calculateDepth(node.right);
int currentDiameter = leftDepth + rightDepth;
maxDiameter = Math.max(maxDiameter,
currentDiameter);

52 | P a g e
return Math.max(leftDepth, rightDepth) + 1;
}
}

3. OUTPUT (PASTE SCREEN-SHOT)

53 | P a g
e
EXPERIMENT NO. :27
AIM : Balanced Binary Tree

PROGRAM :

1.DESCRIPTION (INTRODUCTION)

The Balanced Binary Tree program checks if a binary tree is


balanced, meaning the height of the left and right subtrees of
every node differs by no more than one. It uses a recursive
approach to calculate the height and balance of each
subtree.

2.SOURCE CODE (TYPED)


class Solution {
public boolean isBalanced(TreeNode

root) { if (root == null) return

true;

if (Height(root) == -1) return false;


return true;
}

public int Height(TreeNode root) {


// Base case...
if (root == null) return 0;
// Height of left subtree...

54 | P a g
e
int leftHeight = Height(root.left);
// Height of height subtree...
int rightHight = Height(root.right);
// In case of left subtree or right subtree unbalanced,
return -1... if (leftHeight == -1 || rightHight == -1)
return -1;
// If their heights differ by more than ‘1’,
return -1... if (Math.abs(leftHeight -
rightHight) > 1) return -1;
// Otherwise, return the height of this subtree as
max(leftHeight, rightHight) + 1...
return Math.max(leftHeight, rightHight) + 1;
}
}

3.OUTPUT (PASTE SCREEN-SHOT)

55 | P a g
e
EXPERIMENT NO. :28
AIM : Lowest Common Ancestor of a Binary Tree

PROGRAM :

1.DESCRIPTION

The Lowest Common Ancestor of a Binary Tree program finds the


lowest common ancestor (LCA) of two nodes in a binary
tree. It recursively traverses the tree to find the deepest
node that is an ancestor of both target nodes.

2.SOURCE CODE
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode
p, TreeNode q) {
// Base case: if the current node is null, or if we have found
p or q if (root == null || root == p || root == q) {
return root;
}

// Search in the left and right subtrees


TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p,
q);

// If both left and right are non-null, the current node is the
LCA if (left != null && right != null) {
return root;
}

56 | P a g e
// Otherwise, return the non-null value (either left or right, or
null if neither found)
return left != null ? left : right;
}
}

3.OUTPUT (PASTE SCREEN-SHOT)

57 | P a g e
EXPERIMENT NO. :29
AIM : Course Schedule

PROGRAM :

1.DESCRIPTION

The Course Schedule program determines if it's possible to


complete all
courses given prerequisites. It models the problem as a directed
graph and uses topological sorting or cycle detection (via DFS or
Kahn's algorithm)
to check for any cycles, indicating whether all courses can be
completed.

2.SOURCE CODE
class Solution {
public boolean canFinish(int n, int[][] pre) {

boolean visited[] = new


boolean[n]; boolean helper[] =
new boolean[n];
ArrayList<ArrayList<Integer>> al = new ArrayList<>();

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


{}
a l .a d d ( n e w ArrayList());
for (i n t [] t : p r e)
{}
for(int i = 0; i < n; i++)

al.get( t[1] ).add( t[0] );


58 | P a g e
{
if(visited[i] == false)
{
boolean ans = dfs_cyclicDetection(al, i , visited ,
helper); if(ans)
return false;
}
}
return true;
}
public static boolean
dfs_cyclicDetection( ArrayList<ArrayList<Integer>> al, int i,
boolean visited[], boolean helper[]) {

visited[i] = true;
helper[i] = true;
ArrayList< Integer > neighbour = al.get(i);

for(int k = 0; k < neighbour.size(); k++)


{
int curr = neighbour.get(k);
if(helper[curr] == true) return
true;
if(visited[curr] == false)
{
boolean ans =
dfs_cyclicDetection(al,curr,visited,helper); if(ans ==
true) return true;
}
}
helper[i] =
false; return
false;
}
}

59 | P a g
e
3.OUTPUT

60 | P a g
e
EXPERIMENT NO. :30
AIM Course Schedule II

PROGRAM :

1.DESCRIPTION (INTRODUCTION)

The Course Schedule II program returns the order in which courses


should
be taken to finish all courses, considering their prerequisites. It
uses topological sorting (via Kahn's algorithm or DFS) to find a valid
order, or detects if a cycle exists, indicating no valid order.

2.SOURCE CODE (TYPED)


import java.util.*;

class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites)
{ List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}
int[] inDegree = new

int[numCourses]; for (int[] prereq

: prerequisites) {

int course = prereq[0];


int prerequisite = prereq[1];
graph.get(prerequisite).add(cour
se); inDegree[course]++;
}
Queue<Integer> queue = new LinkedList<>();
61 | P a g
e
for (int i = 0; i < numCourses; i+
+) { if (inDegree[i] == 0) {
queue.offer(i);
}
}
List<Integer> order = new ArrayList<>();

while (!queue.isEmpty()) {
int current =
queue.poll();
order.add(current);

for (int neighbor :


graph.get(current)) {
inDegree[neighbor]--;
// If in-degree becomes 0, add to the queue.
if (inDegree[neighbor] == 0) {
queue.offer(neighbor);
}
}
}
if (order.size() != numCourses) {
return new int[0];
}

return order.stream().mapToInt(i -> i).toArray();


}
}

3.OUTPUT (PASTE SCREEN-SHOT)

62 | P a g
e
EXPERIMENT NO. :31
AIM : Number of Operations to Make Network Connected

PROGRAM :

1.DESCRIPTION (INTRODUCTION)

The Number of Operations to Make Network Connected program


calculates the minimum number of operations required to connect
all computers in a network, given their direct connections. It uses a
graph traversal (like DFS or BFS) to count disconnected
components and determine the necessary operations to
connect them.

2.SOURCE CODE (TYPED)


class Solution {
public int makeConnected(int n, int[][]
connections) { if (connections.length < n -
1) {
return -1;
}

int[] parent = new int[n];


int[] rank = new int[n];
for (int i = 0; i < n; i+
+) {
parent[i] = i;
rank[i] = 0;
}
int find(int node) {
if (parent[node] != node) {
parent[node] = find(parent[node]); // Path compression.
}
return parent[node];
63 | P a g e
}

void union(int node1, int


node2) { int root1 =
find(node1);
int root2 = find(node2);
if (root1 != root2) {
if (rank[root1] > rank[root2]) {
parent[root2] = root1;
} else if (rank[root1] < rank[root2]) {
parent[root1] = root2;
} else {
parent[root2] = root1;
rank[root1]++;
}
}
}
for (int[] connection : connections) {
union(connection[0], connection[1]);
}

int components =
0; for (int i = 0; i < n;
i++) {
if (find(i) == i) {
components++;
}
}
return components - 1;
}
}
3.OUTPUT

64 | P a g
e
EXPERIMENT NO. :33
AIM Min Cost to Connect All Points

PROGRAM :

1.DESCRIPTION (INTRODUCTION)

The Min Cost to Connect All Points program finds the minimum cost to
connect all points in a 2D plane, where the cost to connect
two points is the Manhattan distance between them. It uses a
Minimum Spanning Tree algorithm (like Prim's or Kruskal's) to
efficiently compute the minimum cost.

2.SOURCE CODE
class Solution {

public int minCostConnectPoints(int[][]


points) { int res = 0;
int numVisited = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
int[] minDist = new int[points.length];
Arrays.fill(minDist, Integer.MAX_VALUE);
// Start with the first point
pq.offer(new int[]{0, 0});
while(numVisited < points.length)
{
int[] cur = pq.poll();
if (minDist[cur[0]] < 0) {
continue;
}

65 | P a g
e
minDist[cur[0]] = -
1; res += cur[1];
numVisited++;
for (int i=0; i<points.length; i++) {
if (minDist[i] < 0)
continue; int d = dist(i,
cur[0], points); if (d <
minDist[i]) {
pq.offer(new int[]{i,
d}); minDist[i] = d;
}
}
}
return res;
}
private int dist(int i, int j, int[][] points) {
return Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] -
points[j][1]);
}
}
3.OUTPUT

66 | P a g
e

You might also like