ADSA Lab
ADSA Lab
Lab
File
For
BACHELOR OF
ENGINEERING &
TECHNOLOGY
UTTAR PRADESH
Admission No:
22SCSE1010530 Semester : V
1|Page
EXPERIMENT NO. :22131010830
PROGRAM :
1.DESCRIPTION (INTRODUCTION)
2.SOURCE CODE (TYPED)
2|Page
EXPERIMENT NO. :01
PROGRAM :
1.DESCRIPTION
4|Page
}
}
3.OUTPUT (PASTE SCREEN-SHOT)
5|Page
EXPERIMENT NO. :02
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.
6|Page
EXPERIMENT NO. :03
PROGRAM :
1.DESCRIPTION (INTRODUCTION)
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.
}
for( int k=0;k<count;k++)
{
nums[i]=0; i+
+;
9|Page
}
}
}
10 | P a g
e
EXPERIMENT NO. :05
AIM : To reverse
PROGRAM :
1.DESCRIPTION
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
}
12 | P a g
e
EXPERIMENT NO. :7
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.
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
PROGRAM :
1.DESCRIPTION
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;
}
}
};
21 | P a g
e
EXPERIMENT NO. :12
AIM : Min Stack
PROGRAM :
1.DESCRIPTION
2.SOURCE CODE
class MinStack {
private:
stack<int>
mainStack;
stack<int>
minStack;
public:
MinStack() {}
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();
}
};
24 | P a g
e
EXPERIMENT NO. :13
AIM Valid Parentheses
PROGRAM :
1.DESCRIPTION (INTRODUCTION)
26 | P a g
e
}
}
}
return stk.empty();
}
};
3.OUTPUT
27 | P a g
e
EXPERIMENT NO. :14
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;
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
2.SOURCE CODE
class MyCircularQueue {
private:
vector<int> queue;
int head;
int tail;
int capacity;
int size;
public:
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
2.SOURCE CODE
class MyQueue {
Stack<Integer> stack1 = new
Stack<>(); Stack<Integer> stack2 =
new Stack<>(); public MyQueue()
{
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
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();
return false;
}
}
37 | P a g
e
4.OUTPUT
38 | P a g
e
EXPERIMENT NO. :19
PROGRAM :
1.DESCRIPTION
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
1.DESCRIPTION
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
1.DESCRIPTION
2.SOURCE CODE
class Solution {
LinkedList<Integer> res = new LinkedList<>();
42 | P a g e
3.OUTPUT
43 | P a g
e
EXPERIMENT NO. :22
AIM Binary Tree Inorder Traversal
PROGRAM :
1.DESCRIPTION
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
2.SOURCE CODE
class Solution {
public List<Integer> postorderTraversal(TreeNode
root) { List<Integer> result = new ArrayList<>();
postOrder(root, result);
return result;
}
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
}
return result;
}
}
3.OUTPUT
49 | P a g
e
EXPERIMENT NO. :25
AIM : Maximum Depth of Binary
PROGRAM :
1.DESCRIPTION
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);
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.
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;
}
}
53 | P a g
e
EXPERIMENT NO. :27
AIM : Balanced Binary Tree
PROGRAM :
1.DESCRIPTION (INTRODUCTION)
true;
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;
}
}
55 | P a g
e
EXPERIMENT NO. :28
AIM : Lowest Common Ancestor of a Binary Tree
PROGRAM :
1.DESCRIPTION
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;
}
// 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;
}
}
57 | P a g e
EXPERIMENT NO. :29
AIM : Course Schedule
PROGRAM :
1.DESCRIPTION
2.SOURCE CODE
class Solution {
public boolean canFinish(int n, int[][] pre) {
visited[i] = true;
helper[i] = true;
ArrayList< Integer > neighbour = al.get(i);
59 | P a g
e
3.OUTPUT
60 | P a g
e
EXPERIMENT NO. :30
AIM Course Schedule II
PROGRAM :
1.DESCRIPTION (INTRODUCTION)
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
: prerequisites) {
while (!queue.isEmpty()) {
int current =
queue.poll();
order.add(current);
62 | P a g
e
EXPERIMENT NO. :31
AIM : Number of Operations to Make Network Connected
PROGRAM :
1.DESCRIPTION (INTRODUCTION)
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 {
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