0% found this document useful (0 votes)
15 views215 pages

DS Lab Assign

The document contains a lab file for a data structures course. It includes 8 questions on topics like arrays, vectors, linked lists, and doubly linked lists. For each question, the student has provided C++ code to solve the problem and test various data structures and algorithms.

Uploaded by

sunsam098
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)
15 views215 pages

DS Lab Assign

The document contains a lab file for a data structures course. It includes 8 questions on topics like arrays, vectors, linked lists, and doubly linked lists. For each question, the student has provided C++ code to solve the problem and test various data structures and algorithms.

Uploaded by

sunsam098
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/ 215

Jaypee Institute of Information Technology, Noida

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING AND


INFORMATION TECHNOLOGY

Lab File

9922103003 Samarpreet Singh

Course Name: Data Structures Lab


Course Code: 15B17CI371
Program: B. Tech. IT
2 Year 4 Sem
nd th

2023 - 2024
Week 1 Lab B
Q1.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cout<<"Enter n: ";

cin>>n;

int *arr=new int[n];

int sum=0;

cout<<"now enter "<<n<<" numbers: ";

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

cin>>arr[i];

sum+=arr[i];

float avg=((float)sum)/n;

cout<<"The sum of numbs is: "<<avg;

Q2.
#include<bits/stdc++.h>

using namespace std;

int main(){
map<int,int>mp;

int n;

cout<<"Enter n: ";cin>>n;

int temp=0;

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

cin>>temp;

mp[temp]++;

for(auto i:mp){

cout<<i.first<<" occurs "<<i.second<<" times"<<endl;

Q3.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cout<<"Enter n: ";

cin>>n;

vector<int>v(n-1);

int temp;
cin>>temp;

for(auto &i:v){

cin>>i;

v.push_back(temp);

for(auto &i:v){

cout<<i<<" ";

Q4.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cout<<"Enter n: ";

cin>>n;

if(n<2){

cout<<"Invalid";

vector<int>v(n);
for(auto &i:v){

cin>>i;

sort(v.begin(),v.end());

cout<<"The second smallest element is : "<<v[1];

Week 2 Lab A
Q1.
(a)

Output –

Size of o1 : 4

Size of o2 : 16

Size of abc is :16

(b)

Output –

Size of o1 :4

Size of o2 : 24

(c)

Output-

Size of o1 : 4

Size of o2 : 24

(d)
Output-

Size of o1 : 4

Size of o2 : 24

(e)

Size of o1 : 4

Size of o2 : 16

(f)

Size of o1 : 4

Size of o2 : 20

Q2.
(a) 4.5
(b) 5
(c) 44
(d) error: invalid conversion from 'int*' to 'int'

(e) 5
(f) 4
(g) 5
(h) 1391661613893824345

Q3.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cout<<"Enter n:";

cin>>n;

int *a= new int[n];


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

a[i]=rand()%100;

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

if(i%2==0)

cout<<i<<" ";

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

if(i%2!=0)

cout<<i<<" ";

Week 2 Lab-B
1
#include<bits/stdc++.h>

using namespace std;

class node{

public:

int val;

node* next;

node(int v){
val=v;

next = NULL;

};

int main(){

node* head = new node(0);

node *temp = head;

int v;

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

cout<<"Enter Node "<<i+1<<" -> ";

cin>>v;

temp->next = new node(v);

temp=temp->next;

head = head->next;

cout<<"The Linked List is -> ";

temp=head;

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

cout<<temp->val<<" ";

temp=temp->next;

}
2
#include<bits/stdc++.h>

using namespace std;

class node{

public:

int val;

node* next;

node(int v){

val=v;

next = NULL;

};

int main(){

int n;

cout<<"Enter Number of nodes -> ";

cin>>n;

node* head = new node(0);


node *temp = head;

int v;

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

cout<<"Enter Node "<<i+1<<" -> ";

cin>>v;

temp->next = new node(v);

temp=temp->next;

head = head->next;

int maxi=INT_MIN,mini=INT_MAX;

temp=head;

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

mini=min(mini,temp->val);

maxi=max(maxi,temp->val);

temp=temp->next;

cout<<"Number of Nodes -> "<<n<<endl;

cout<<"Max -> "<<maxi<<endl;

cout<<"Min -> "<<mini<<endl;

}
3
#include<bits/stdc++.h>

using namespace std;

class node{

public:

int val;

node* next;

node(int v){

val=v;

next = NULL;

};

int main(){

int n;

cout<<"Enter Number of nodes -> ";

cin>>n;

node* head = NULL;

int v;

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

cout<<"Enter Node "<<i+1<<" -> ";

cin>>v;

node *temp= new node(v);

if(head==NULL){

head=temp;

continue;

temp->next=head;
head =temp;

node* temp = head;

cout<<"Linked list after adding nodes at beginning -> ";

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

cout<<temp->val<<" ";

temp=temp->next;

4
#include<bits/stdc++.h>

using namespace std;

class node{

public:

int val;

node* next;

node(int v){

val=v;

next = NULL;

}
};

int main(){

int n;

cout<<"Enter Number of nodes -> ";

cin>>n;

node* head = new node(0);

node* temp = head;

int v;

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

cout<<"Enter Node "<<i+1<<" -> ";

cin>>v;

temp->next= new node(v);

temp = temp->next;

head = head->next;

temp = head;

int x;

int y;

cout<<endl;

cout<<"Enter new node -> ";

cin>>y;

node* newNode = new node(y);

cout<<"Enter Location -> ";

cin>>x;

for(int i=1;i<x-1;i++){

temp=temp->next;

newNode->next=temp->next;

temp->next = newNode;
cout<<"Now the linkedList is -> ";

temp = head;

while(temp!=NULL){

cout<<temp->val<<" ";

temp = temp->next;

5
#include<bits/stdc++.h>

using namespace std;

class node{

public:

int val;

node* next;

node(int v){

val=v;

next = NULL;

};

int main(){

int n;

cout<<"Enter Number -> ";

cin>>n;

node* head = NULL;

int v;
while(n!=0){

v = n%10;

n/=10;

node* temp =new node(v);

if(head==NULL){

head=temp;

continue;

temp->next= head;

head = temp;

node* temp = head;

cout<<"Now the linkedList is : ";

temp = head;

while(temp!=NULL){

cout<<temp->val<<" -> ";

temp = temp->next;

cout<<"NULL";

6
#include<bits/stdc++.h>

using namespace std;


class node{

public:

char val;

node* next;

node(char v){

val=v;

next = NULL;

};

int main(){

string s;

cout<<"Enter Name -> ";

cin>>s;

node* head = NULL;

char v;

while(s.length()!=0){

v = s[s.length()-1];

s = s.substr(0,s.length()-1);

node* temp =new node(v);

if(head==NULL){

head=temp;

continue;

temp->next= head;

head = temp;

node* temp = head;


cout<<"The linkedList is : ";

temp = head;

while(temp!=NULL){

cout<<temp->val<<" -> ";

temp = temp->next;

cout<<"NULL";

temp = head;

while(temp->val=='a' || temp->val=='e' || temp->val=='i' || temp->val=='o' || temp->val=='u'){

node* del = temp;

temp = temp->next;

delete del;

node* head1 = temp;

while(temp!=NULL){

if(temp->next && (temp->next->val=='a' || temp->next->val=='e' || temp->next->val=='i' ||


temp->next->val=='o' || temp->next->val=='u')){

node *del = temp->next;

temp->next = temp->next->next;

delete del;

continue;

temp = temp->next;

cout<<endl<<"linkedList after removing vovels : ";

temp = head1;

while(temp!=NULL){

cout<<temp->val<<" -> ";

temp = temp->next;
}

cout<<"NULL";

7
#include<bits/stdc++.h>

using namespace std;

class node{

public:

char val;

node* next;

node(char v){

val=v;

next = NULL;

};

void remove(node* &head1,node* &head2){

int j = -1;

int count =0;

node* temp1 = head1;


node* temp2 = head2;

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

if(temp1->val == temp2->val){

if(j==-1){

j=i;

count++;

if(count==3){

break;

else{

j=-1;

count=0;

temp1 = head1;

if(count==3){

if(j==0){

head1 = head1->next->next->next;

else{

for(int i=0;i<j-1;i++){

temp1=temp1->next;

temp1->next=temp1->next->next->next->next;

cout<<"Linked List 1 becomes -> ";

temp1 = head1;

while(temp1!=NULL){
cout<<temp1->val<<" -> ";

temp1 = temp1->next;

cout<<"NULL";

int main(){

string s1;

cout<<"Enter Name 1 -> ";

cin>>s1;

node* head1 = NULL;

char v;

while(s1.length()!=0){

v = s1[s1.length()-1];

s1 = s1.substr(0,s1.length()-1);

node* temp1 =new node(v);

if(head1==NULL){

head1=temp1;

continue;

temp1->next= head1;

head1 = temp1;

string s2;

cout<<"Enter Name 2 -> ";

cin>>s2;

node* head2 = NULL;

char v2;

while(s2.length()!=0){

v2 = s2[s2.length()-1];

s2 = s2.substr(0,s2.length()-1);
node* temp2 =new node(v2);

if(head2==NULL){

head2=temp2;

continue;

temp2->next= head2;

head2 = temp2;

remove(head1,head2);

8
#include<bits/stdc++.h>

using namespace std;

struct node{

int data;
node* next;

node* prev;

node(int d){

data=d;

next=NULL;

prev=NULL;

};

int main(){

node* head = NULL;

node* tail;

int n;

cout<<"Enter No of nodes : ";

cin>>n;

int t;

cout<<"Enter Node Values : ";

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

cin>>t;

node* temp = new node(t);

if(head==NULL){

head = temp;

tail = head;

else{

tail->next=temp;

temp->prev=tail;

tail = tail->next;

}
}

cout<<"Linked list -> ";

node* tt = head;

while(tt){

cout<<tt->data<<"<->";

tt=tt->next;

cout<<"NULL"<<endl;

int p;

cout<<"Enter New Node Position : ";

cin>>p;

int x;

cout<<"Enter Value of new node : ";

cin>>x;

node* newNode = new node(x);

node* temp = head;

for(int i=1;i<p-1;i++){

temp = temp -> next;

newNode->next=temp->next;

temp->next->prev=newNode;

temp->next = newNode;

cout<<"Linked List Now -> ";

while(head){

cout<<head->data<<"<->";

head=head->next;

cout<<"NULL";

}
9
#include<bits/stdc++.h>

using namespace std;

struct node{

int data;

node* next;

node* prev;

node(int d){

data=d;

next=NULL;

prev=NULL;

};

int main(){

node* head = NULL;

node* tail;

int n;

cout<<"Enter No of nodes : ";

cin>>n;

int t;

cout<<"Enter Node Values : ";


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

cin>>t;

node* temp = new node(t);

if(head==NULL){

head = temp;

tail = head;

else{

tail->next=temp;

temp->prev=tail;

tail = tail->next;

cout<<"Linked list -> ";

node* tt = head;

while(tt){

cout<<tt->data<<"<->";

tt=tt->next;

cout<<"NULL"<<endl;

node* temp = head;

while(temp->next!=tail){

temp = temp->next;

};

temp->next=NULL;

delete tail;

tail = temp;

cout<<"Linked List After deleting Last Node -> ";

while(head){

cout<<head->data<<"<->";
head=head->next;

cout<<"NULL";

10
#include<bits/stdc++.h>

using namespace std;

struct node{

int data;

node* next;

node* prev;

node(int d){

data=d;

next=NULL;

prev=NULL;

};

int main(){

node* head = NULL;

node* tail;

int n;

cout<<"Enter No of nodes : ";

cin>>n;

int t;
cout<<"Enter Node Values : ";

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

cin>>t;

node* temp = new node(t);

if(head==NULL){

head = temp;

tail = head;

else{

tail->next=temp;

temp->prev=tail;

tail = tail->next;

cout<<"Linked list -> ";

node* tt = head;

while(tt){

cout<<tt->data<<"<->";

tt=tt->next;

cout<<"NULL"<<endl;

node* temp1 = head;

node* temp2 = tail;

int i=1;

while(temp1!=temp2){

int t = temp1->data;

temp1->data=temp2->data;

temp2->data=t;

cout<<"Linked List After CALL"<<i++<<"-> ";

node* temp = head;


while(temp){

cout<<temp->data<<"<->";

temp=temp->next;

cout<<"NULL"<<endl;

temp1=temp1->next;

if(temp1==temp2){break;}

temp2=temp2->prev;

Week 3 Lab A
1.
#include<bits/stdc++.h>

using namespace std;

struct node{

int data;

node* next;

node(int val){

data=val;

next=NULL;

}
};

void addNode(node* &rear,int val){

node* curr=new node(val);

if(rear==NULL){

rear=curr;

rear->next=curr;

return;

curr->next=rear->next;

rear->next=curr;

rear=curr;

return;

void delet(node* &rear,int loc){

if(loc==0){

node* toDel = rear->next;

rear->next=rear->next->next;

delete toDel;

return;

node*temp=rear->next;

int trav=1;

while(trav<loc){

temp=temp->next;

trav++;

if(temp->next==rear){

temp->next=temp->next->next;

delete rear;
rear=temp;

return;

temp->next=temp->next->next;

return;

void printL(node* &rear){

node*temp=rear->next;

do{

cout<<temp->data<<"->";

temp=temp->next;

}while(temp!=rear->next);

int main(){

node* rear=NULL;

int n;

cout<<"Enter n: ";

cin>>n;

int temp;

cout<<"Enter n nums: "<<endl;

while(n--){

cin>>temp;

addNode(rear,temp);

printL(rear);

cout<<endl;

cout<<"Enter loc to delete: ";

cin>>temp;
delet(rear,temp);

cout<<endl;

printL(rear);

2.
#include<bits/stdc++.h>

using namespace std;

struct node{

int data;

node* next;

node(int val){

data=val;

next=NULL;

};

void addNode(node* &rear,int val){

node* curr=new node(val);

if(rear==NULL){

rear=curr;

rear->next=curr;

return;

}
curr->next=rear->next;

rear->next=curr;

rear=curr;

return;

node* concat(node* rear1,node*rear2){

if(!rear1 || !rear2){

return NULL;

node* head=rear1->next;

rear1->next=rear2->next;

rear2->next=head;

return rear2;

void printL(node* &rear){

node*temp=rear->next;

do{

cout<<temp->data<<"->";

temp=temp->next;

}while(temp!=rear->next);

int main(){

node* rear1=NULL;

int n;

cout<<"Enter n1: ";

cin>>n;

int temp;

cout<<"Enter n1 nums: "<<endl;


while(n--){

cin>>temp;

addNode(rear1,temp);

printL(rear1);

node* rear2=NULL;

cout<<endl;

cout<<"Enter n2: ";

cin>>n;

cout<<"Enter n2 nums: "<<endl;

while(n--){

cin>>temp;

addNode(rear2,temp);

printL(rear2);

cout<<endl;

cout<<"After concat: "<<endl;

node* rear=concat(rear1,rear2);

printL(rear);

}
4.
#include<bits/stdc++.h>

using namespace std;

struct node{

int data;

node* next;

node(int val){

data=val;

next=NULL;

};

void addNode(node* &head,int val){

node*curr=new node(val);

if(head==NULL){

head=curr;

return;

node* temp=head;

while(temp->next){
temp=temp->next;

temp->next=curr;

return;

void printL(node* head){

node* temp=head;

while(temp){

cout<<temp->data<<"->";

temp=temp->next;

cout<<endl;

int main(){

node* head1=NULL;

int n;

cout<<"Enter n1: ";

cin>>n;

int x;

cout<<"Enter n1 nums: "<<endl;

while(n--){

cin>>x;

addNode(head1,x);

node* head2=NULL;

cout<<endl;

cout<<"Enter n2: ";

cin>>n;
cout<<"Enter n2 nums: "<<endl;

while(n--){

cin>>x;

addNode(head2,x);

int num1=0,num2=0;

node* temp=head1;

while(temp){

num1=((num1*10)+temp->data);

temp=temp->next;

temp=head2;

while(temp){

num2=((num2*10)+temp->data);

temp=temp->next;

cout<<endl<<"The mul of two nums is: ";

cout<<num1*num2;

}
5.

#include<bits/stdc++.h>

using namespace std;

struct node{

int data;

node* next;

node(int d){

data=d;

next=NULL;

};

class List{

public:

node* head;

node* tail;

List(){

head=NULL;

tail=NULL;

void Addback(int data){

node* curr = new node(data);

if(!head){

head=curr;

tail=curr;

tail->next=curr;

tail=tail->next;
}

void display(){

node* temp=head;

cout<<endl;

while(temp){

cout<<temp->data;

temp=temp->next;

if(temp){

cout<<" -> ";

void rotateRight(){

node* temp=head;

while(temp->next!=tail){

temp=temp->next;

tail->next=head;

temp->next=NULL;

head=tail;

tail=temp;

};

int main(){

cout<<"Enter n: ";

int n;cin>>n;

int temp;

List l;

while(n--){
cin>>temp;

l.Addback(temp);

cout<<"Original List: ";

l.display();

cout<<endl<<"Now, Updated List: ";

l.rotateRight();

l.display();

6.
#include<bits/stdc++.h>

using namespace std;

struct Node

int data;

Node *next;

};

void splitList( Node *head, Node * &head1_ref, Node * &head2_ref)

Node *slow_ptr = head;

Node *fast_ptr = head;


if(head == NULL)

return;

while(fast_ptr->next != head &&

fast_ptr->next->next != head)

fast_ptr = fast_ptr->next->next;

slow_ptr = slow_ptr->next;

if(fast_ptr->next->next == head)

fast_ptr = fast_ptr->next;

head1_ref = head;

if(head->next != head)

head2_ref = slow_ptr->next;

fast_ptr->next = slow_ptr->next;

slow_ptr->next = head;

void push( Node * &head_ref, int data)

Node *ptr1 = ( Node *)malloc(sizeof( Node));

Node *temp = head_ref;

ptr1->data = data;

ptr1->next = head_ref;

if(head_ref != NULL)
{

while(temp->next != head_ref)

temp = temp->next;

temp->next = ptr1;

else

ptr1->next = ptr1;

head_ref = ptr1;

void printList( Node *head)

Node *temp = head;

if(head != NULL)

printf("\n");

do {

printf("%d ", temp->data);

temp = temp->next;

} while(temp != head);

int main()

int list_size, i;

Node *head = NULL;

Node *head1 = NULL;

Node *head2 = NULL;

push(head, 12);

push(head, 56);
push(head, 2);

push(head, 11);

cout << "Original Circular Linked List";

printList(head);

splitList(head, head1, head2);

cout << "\nFirst Circular Linked List";

printList(head1);

cout << "\nSecond Circular Linked List";

printList(head2);

return 0;

Week 6 A

1.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;cin>>n;
vector<int>v;

int temp;

while(n--){

cin>>temp;

v.push_back(temp);

int x;cin>>x;

for(int i=0;i<v.size();i++){

if(v[i]==x){

cout<<"True"<<endl;

exit(0);

cout<<"False";

2.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;cin>>n;
vector<int>v;

int temp;

while(n--){

cin>>temp;

v.push_back(temp);

sort(v.begin(),v.end());

int x;cin>>x;

int left=0;

int right=v.size()-1;

int mid;

while(left<=right){

mid=(left+right)/2;

if(v[mid]==x){

cout<<"True";

exit(0);

else if(v[mid]>x){

right=mid-1;

else{

left=mid+1;

cout<<"False";

}
3.
#include<bits/stdc++.h>

using namespace std;

int ms(vector<int>v,int k){

int n=v.size();

if(n<k){

return -1;

if(n==1){

return v[0];

vector<int>v1,v2,v3;

int ran=v[n/2];

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

if(v[i]==ran){

v2.push_back(v[i]);

else if(v[i]>ran){

v3.push_back(v[i]);

else{

v1.push_back(v[i]);

}
}

if(v1.size()>=k){

return ms(v1,k);

else if((v1.size()+v2.size())>=k){

return ms(v2,k-v1.size());

else{

return ms(v3,k-v1.size()-v2.size());

int main(){

vector<int>v;

int n;cin>>n;

int temp;

while(n--){

cin>>temp;

v.push_back(temp);

int k;

cin>>k;

cout<<ms(v,k);

4.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;cin>>n;

vector<int>v;

int temp;

while(n--){

cin>>temp;

v.push_back(temp);

sort(v.begin(),v.end());

int x;cin>>x;

int left=0;

int right=v.size()-1;

int mid;

while(left<=right){

mid=left+((x-v[left])*(right-left))/(v[right]-v[left]);

if(v[mid]==x){

cout<<"True";

exit(0);

else if(v[mid]>x){

right=mid-1;

else{

left=mid+1;

cout<<"False";
}

5.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;cin>>n;

vector<string>v;

string temp;

while(n--){

cin>>temp;

v.push_back(temp);

string x;cin>>x;

int left=0;

int right=v.size()-1;

int mid;

sort(v.begin(),v.end());

while(left<=right){

mid=(left+right)/2;

if(v[mid]==x){

cout<<"True";

exit(0);

}
else if(v[mid]>x){

right=mid-1;

else{

left=mid+1;

cout<<"False";

Week 3 Lab-B
Stack Implementation:-
struct node{

int data;

node* next;

node(int d){

data=d;

next=NULL;

};

class Stack{
node* t;

int n=0;

public:

Stack(){

t=NULL;

void push(int val){

n++;

node* curr=new node(val);

if(!t){

t=curr;

return;

curr->next=t;

t = curr;

bool empty(){

return n==0;

void pop(){

if(!t){

cout<<"Stack UnderFlow";

exit(0);

n--;

t=t->next;

int top(){

if(!t){

cout<<"Stack UnderFlow";

exit(0);
}

return t->data;

int size(){

return n;

};

Queue Implementation:-
struct node{

int data;

node* next;

node(int d){

data=d;

next=NULL;

};

class Queue{

node* tail;

node* head;

int n=0;

public:

Queue(){

tail=NULL;

head=NULL;

void push(int val){

n++;

node* curr=new node(val);

if(!head){

head=curr;
tail=curr;

return;

tail->next=curr;

tail=tail->next;

bool empty(){

return n==0;

void pop(){

if(n==0){

cout<<"Stack UnderFlow";

exit(0);

n--;

head=head->next;

int front(){

if(n==0){

cout<<"Stack UnderFlow";

exit(0);

return head->data;

int size(){

return n;

};

1.
x=3 y=9 7 13 4 7
2.
#include<bits/stdc++.h>

using namespace std;

bool isPrime(int x){

for(int i=2;i*i<=x;i++){

if(x%i==0){

return false;

return true;

int main(){

Stack st;

cout<<"Enter a + int: ";

int x;cin>>x;

for(int i=2;i<=x/2;i++){

if(x%i==0 && isPrime(i)){

st.push(i);

cout<<"Prime factors are: ";

while(!st.empty()){

cout<<st.top()<<" ";

st.pop();

}
3.
#include<bits/stdc++.h>

using namespace std;

int main(){

Stack st;

Stack st1;

Stack st2;

cout<<"Enter n: ";

int n;cin>>n;

cout<<"Enter n nums: "<<endl;

int temp;

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

cin>>temp;

st.push(temp);

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

st1.push(st.top());

st.pop();

while(!st.empty()){

st2.push(st.top());

st.pop();

while(!st1.empty()){st.push(st1.top());st1.pop();}

while(!st2.empty()){st.push(st2.top());st2.pop();}
while(!st.empty()){

cout<<st.top()<<" ";

st.pop();

4.

#include<bits/stdc++.h>

using namespace std;

int main(){

cout<<"Enter the decimal num: ";

int n;cin>>n;

cout<<"Enter Base: ";

int x;cin>>x;

Stack st;

while(n!=0){

st.push(n%x);

n/=x;

while(!st.empty()){

cout<<st.top();

st.pop();
}

5.
#include<bits/stdc++.h>

using namespace std;

int main(){

cout<<"Enter String: ";

string s;cin>>s;

Stack st;

for(auto &i:s){

if(i=='(' || i=='[' || i=='{'){

st.push(i);

else if(i==')'){

if(st.top()!='('){break;}

else{st.pop();}

else if(i=='}'){

if(st.top()!='{'){break;}

else{st.pop();}

else if(i==']'){

if(st.top()!='['){break;}
else{st.pop();}

if(!st.empty()){

cout<<"Wrong";

else{

cout<<"Right";

6.
#include<bits/stdc++.h>

using namespace std;

int main(){

cout<<"Enter String: ";

string s;getline(cin,s);
Queue q;

for(int i=0;i<s.length();i++){

if(s[i]!= ' ')

q.push(s[i]);

string ans="";

while(!q.empty()){

if(ans.length()==0){

ans+=q.front();

q.pop();

else{

int cnt=1;

while(!q.empty() && q.front()==ans[ans.length()-1]){

cnt++;

q.pop();

if(cnt!=1){

ans+=to_string(cnt);

else{

ans+=q.front();

q.pop();

cout<<ans;

8.
#include<bits/stdc++.h>

using namespace std;

int main(){

Queue q;

Queue temp;

int n;cin>>n;

int t;

int cnt=0;

while(cnt<n){cin>>t;q.push(t);cnt++;}

int x;cin>>x;

x--;

cnt=0;

int g;

while(cnt<n){

temp.push(q.front());

q.pop();

cnt++;

if(cnt==x){

g=q.front();

q.pop();

cnt++;

q.push(g);

while(!temp.empty()){
q.push(temp.front());

temp.pop();

while(!q.empty()){

cout<<q.front()<<"";

q.pop();

9.
#include<bits/stdc++.h>

using namespace std;

int main(){

Queue q;

Stack st;

string s;

cin>>s;

char x;

for(auto &i:s){

x=tolower(i);

q.push(x);

st.push(x);
}

while(!q.empty()){

if(q.front()!=st.top()){

cout<<"It is not a palindrome";

return 0;

st.pop();q.pop();

cout<<"It is a Palindrome";

10.
#include<bits/stdc++.h>

using namespace std;

int main(){

string s;

cin>>s;

int xl,xf,yf,yl;

bool fly=0,flx=0;

for(int i=0;i<s.length();i++){

if(s[i]=='X'){

if(!flx){

xf=i;

xl=i;
flx=1;

else{

xl=i;

if(s[i]=='Y'){

if(!fly){

yf=i;

yl=i;

fly=1;

else{

yl=i;

int sta=max(xf,yf);

int ed=min(yl,xl);

Stack st;

for(int i=sta+1;i<ed;i++){

st.push(s[i]);

while(!st.empty()){

cout<<st.top()<<" ";

st.pop();

}
Week 4 Lab-A
1.
#include<bits/stdc++.h>

using namespace std;

struct node{

int val;

node* next;

node* prev;

node(){}

node(int x){

val = x;

next=NULL;

};

class Stack{

public:

node* top;

Stack(){

top=NULL;

void push(int x){

if(top==NULL){

top= new node(x);

}
else{

node* temp = new node(x);

temp -> next = top;

top = temp;

void pop(){

node* del = top;

top = top->next;

delete del;

int Top(){

return top->val;

bool isEmpty(){

if(top==NULL){return 1;}return 0;

};

void sortedInsert(Stack &st,int x){

if(st.isEmpty() || x>st.Top()){

st.push(x);

else{

int t = st.Top();

st.pop();

sortedInsert(st,x);

st.push(t);

void sortStack(Stack &st){


if(!(st.isEmpty())){

int n = st.Top();

st.pop();

sortStack(st);

sortedInsert(st,n);

int main(){

Stack st;

int n;

cout<<"Enter Number of elements -> ";

cin>>n;

int temp;

cout<<"Enter elements -> ";

while(n--){

cin>>temp;

st.push(temp);

cout<<"Sorted Stack -> ";

sortStack(st);

while(!st.isEmpty()){

cout<<st.Top()<<" ";

st.pop();

}
2.
#include<bits/stdc++.h>

#include<vector>

using namespace std;

bool isPalindrome(string s){

int n =s.length();

for(int i=0;i<n/2;i++){

if(s[i]!=s[n-i-1]){

return false;

return true;

void rec(string &s,vector<string>&v,int idx,vector<vector<string> > &ans){

if(s.length()==idx){

ans.push_back(v);

return;

string temp;

for(int i=idx;i<s.length();i++){

temp+=s[i];

if(isPalindrome(temp)){

v.push_back(temp);

rec(s,v,i+1,ans);

v.pop_back();

}}}

int main(){

vector<vector<string> >ans;

string s;

cout<<"Enter string-> ";

cin>>s;
vector<string>v;

rec(s,v,0,ans);

for(int i=0;i<ans.size();i++){

for(int j=0;j<ans[i].size();j++){

cout<<ans[i][j]<<" ";

cout<<endl;

3.
#include<bits/stdc++.h>

using namespace std;

struct node{

char val;

node* next;

node* prev;

node(){}

node(char x){

val = x;

next=NULL;

};
class Stack{

public:

node* top;

Stack(){

top=NULL;

void push(char x){

if(top==NULL){

top= new node(x);

else{

node* temp = new node(x);

temp -> next = top;

top = temp;

void pop(){

node* del = top;

top = top->next;

delete del;

char Top(){

return top->val;

bool isEmpty(){

if(top==NULL){return 1;}return 0;

};

int main(){
Stack st;

string s;

cout<<"Enter string -> ";

cin>>s;

for(int i=0;i<s.length();i++){

st.push(s[i]);

s="";

while(!st.isEmpty()){

s+=st.Top();

st.pop();

cout<<"Reverse String -> "<<s;

4.
#include <iostream>

using namespace std;

void TOH(int n, char Sour, char Aux, char Des)

if (n == 1) {

cout << "Move Disk " << n << " from " << Sour << " to " << Des << endl;

return;

TOH(n - 1, Sour, Des, Aux);

cout << "Move Disk " << n << " from " << Sour << " to " << Des << endl;
TOH(n - 1, Aux, Sour, Des);

int main()

int n;

cout << "Enter no. of disks:";

cin >> n;

TOH(n, 'A', 'B', 'C');

return 0;

5.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cout<<"Enter Number -> ";

cin>>n;

while(n!=1){

cout<<n<<" ";

if(n%2==0){

n/=2;
}

else{

n*=3;

n++;

cout<<1;

Week 6 B

1.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cout<<"Enter Range -> ";

cin>>n;

vector<int>arr;

int temp;

int x = 0;

cout<<"Enter elements -> ";

for(int i=0;i<n;i++){
cin>>temp;

arr.push_back(temp);

x=x^temp;

x=x^(i+1);

int a;

a=(x&~(x-1));

int xa=0;

int xb=0;

for(int i=0;i<arr.size();i++){

if((arr[i]&a)!=0){

xa=xa^arr[i];

else{

xb=xb^arr[i];

for (int i = 1; i <= n; i++) {

if ((i & a) != 0) {

xa=xa^i;

else {

xb=xb^i;

int c=0;

for(int i=0;i<arr.size();i++){

if(arr[i]==xa){

c++;

if(c==2){
cout<<"Missing = "<<xb<<endl;

cout<<"Repeating = "<<xa;

else{

cout<<"Missing = "<<xa<<endl;

cout<<"Repeating = "<<xb;

2.
#include<bits/stdc++.h>

using namespace std;

int main(){

int n;

cout<<"Enter Number of elements -> ";

cin>>n;

vector<int>arr;

int temp;

cout<<"Enter elements -> ";

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

cin>>temp;

arr.push_back(temp);

int x;

bool flag=0;
cout<<"Enter X -> ";

cin>>x;

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

if(arr[i]>=x){

flag = 1;

if(arr[i]==x){

cout<<" Floor and Ceil both are "<<x;

else if(i>0){

cout<<"Floor -> "<<arr[i-1]<<endl;

cout<<"Ceil -> "<<arr[i];

else{

cout<<"Floor Does Not exist"<<endl;

cout<<"Ceil -> "<<arr[i];

break;

if(!flag){

cout<<"Floor -> "<<temp<<endl;

cout<<"Ceil Does Not exist";

}
3.
#include<bits/stdc++.h>

using namespace std;

int main(){

int x;

cout<<"Enter Element to be found -> ";

cin>>x;

int n;

cout<<"Enter Number of elements -> ";

cin>>n;

bool flag=0;

int temp;

unordered_set<int>s;

cout<<"Enter elements -> ";

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

cin>>temp;

s.insert(temp);

auto it = s.find(abs(x-temp));

if(it!=s.end()){

flag =1;

cout<<"Pair Found: ("<<*it<<","<<temp<<")"<<endl;


}

if(!flag){

cout<<"Pair Not Found";

4.
#include<bits/stdc++.h>

using namespace std;

int rec(int &n,int m){

if(m==0){

return 0;

return n+rec(n,m-1);

int main(){

int n , m;

cout<<"Enter Two Numbers -> ";

cin>>n>>m;

cout<<"Multiplication Using recursion -> "<<rec(n,m);

}
5.
#include<bits/stdc++.h>

using namespace std;

int hcf(int n1, int n2) {

if (n2 != 0)

return hcf(n2, n1 % n2);

else

return n1;

int main(){

int n , m;

cout<<"Enter Two Numbers -> ";

cin>>n>>m;

cout<<"LCM Using recursion -> "<<(n*m)/hcf(n,m);

6.
#include<bits/stdc++.h>

using namespace std;

int rec(int n){


if (n == 0)

return 0;

return pow(n,n) + rec(n-1);

int main(){

int n;

cout<<"Enter N -> ";

cin>>n;

cout<<"Sum of Series Using recursion -> "<<rec(n);

Week 7 A

1.
#include<bits/stdc++.h>

using namespace std;

vector<string>ans;

void permu(string &s,int idx){

if(idx==s.length()){

ans.push_back(s);
return;

for(int i=idx;i<s.size();i++){

swap(s[i],s[idx]);

permu(s,idx+1);

swap(s[i],s[idx]);

int main(){

string s;

cout<<"Enter string -> ";

cin>>s;

permu(s,0);

sort(ans.begin(),ans.end());

cout<<"Permutations -> ";

for(int i=0;i<ans.size();i++){

cout<<ans[i]<<" ";

2.
#include<bits/stdc++.h>

using namespace std;


vector<string>ans;

int merge(vector<int>&v,int low,int mid,int high){

vector<int>temp;

int i = low;

int j = mid+1;

int c=0;

while(i<=mid && j<=high){

if(v[i]<=v[j]){

temp.push_back(v[i]);

i++;

else{

c+=(mid-i+1);

temp.push_back(v[j]);

j++;

while(i<=mid){

temp.push_back(v[i]);

i++;

while(j<=high){

temp.push_back(v[j]);

j++;

for(int k=low;k<=high;k++){

v[k]=temp[k-low];

return c;

}
int mergeSort(vector<int>&v,int low,int high){

if(low>=high){

return 0;

int mid = (low+high)/2;

int c=0;

c+=mergeSort(v,low,mid);

c+=mergeSort(v,mid+1,high);

c+=merge(v,low,mid,high);

return c;

int main(){

int n;

cout<<"Enter no of Elements -> ";

cin>>n;

vector<int>v(n);

cout<<"Enter Elements -> ";

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

cin>>v[i];

cout<<"Inversion Count -> ";

cout<<mergeSort(v,0,n-1);

}
3.
#include<bits/stdc++.h>

using namespace std;

int median (vector<int>arr,int k){

int n=arr.size()-1;

int m = n/2;

vector<int>a1;

vector<int>a2;

vector<int>a3;

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

if(arr[i]<arr[m]){

a1.push_back(arr[i]);

else if(arr[i]>arr[m]){

a3.push_back(arr[i]);

else{

a2.push_back(arr[i]);

int x =a1.size()+a2.size();

if(a1.size()>=k){

return median(a1,k);

else if(x>=k){

return arr[m];

else{

return median(a3,k-x);

}
}

int main(){

int n;

cout<<"Enter number of elements -> ";

cin>>n;

cout<<"Enter elements -> ";

vector<int>arr(n);

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

cin>>arr[i];

cout<<"Enter k -> ";

int k;

cin>>k;

cout<<k<<" smallest element -> "<<median(arr,k);

4.
#include<bits/stdc++.h>

using namespace std;

int minSwaps(vector<int>&arr){

vector<int>temp(arr.size());
map< int,int >m;

for(int i=0;i<temp.size();i++){

m[arr[i]]=i;

temp[i]=arr[i];

sort(temp.begin(),temp.end());

int ans=0;

for(int i=0;i<arr.size();i++){

if(arr[i]!=temp[i]){

ans++;

swap(arr[i],arr[m[temp[i]]]);

m[temp[i]]=i;

m[arr[i]]=m[temp[i]];

return ans;

int main(){

int n;

cout<<"Enter number of elements -> ";

cin>>n;

cout<<"Enter elements -> ";

vector<int>arr(n);

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

cin>>arr[i];

cout<<"Min No. of Swaps -> "<<minSwaps(arr);

}
Week 7 B
1.
#include<bits/stdc++.h>

using namespace std;

struct node{

int data;

node* down;

node* next;

node(int v){

data=v;

down=NULL;

next=NULL;

};

void flatten(node* &head){

if(!head || !head->next){

return;

node* tail =head;

node*start =head;
while(tail->next){

tail=tail->next;

while(start!=tail){

if(start->down){

tail->next=start->down;

while(tail->next){

tail=tail->next;

start=start->next;

return;

node* listf(int arr[],int n){

node* head=new node(arr[0]);

if(n==1){

return head;

node* temp =head;

for(int i=1;i<n;i++){

temp->next=new node(arr[i]);

temp=temp->next;

return head;

int main(){

int arr1[]={1,2,3};

int arr2[]={4,5};

int arr3[]={6};

int arr4[]={7};
int arr5[]={8};

int arr6[]={9};

node*head1=listf(arr1,3);

node*head2=listf(arr2,2);

node*head3=listf(arr3,1);

node*head4=listf(arr4,1);

node*head5=listf(arr5,1);

node*head6=listf(arr6,1);

head1->down=head2;

head1->next->next->down=head3;

head2->down=head4;

head2->next->down=head5;

head3->down=head6;

flatten(head1);

while(head1){

cout<<head1->data<<"->";

head1=head1->next;

2.
class Solution {

public:

vector<vector<int<> multiply(vector<vector<int<>& A, vector<vector<int<>& B) {

int r1 = A.size();

int r2 = B.size();
int c1 = A[0].size();

int c2 = B[0].size();

vector < vector <int< > ret(r1, vector <int< (c2));

vector < pair <int, int> > sparseA[r1];

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

for(int j = 0; j < c1; j++){

if(A[i][j] != 0)sparseA[i].push_back({j, A[i][j]});

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

for(int j = 0; j < sparseA[i].size(); j++){

for(int k = 0; k < c2; k++){

int x = sparseA[i][j].first;

if(B[x][k] != 0){

ret[i][k] += sparseA[i][j].second * B[x][k];

return ret;

};
3.
#include<bits/stdc++.h>
using namespace std;
bool rat(int i,int j,int n,int m,int **arr,int **ans){
if(ans[i][j]){return false;}
if(i>=n || i<0 || j<0 || j>=m){
return 0;
}
if(i==n-1 && j==m-1){
if(arr[i][j]){
ans[i][j]=1;
return 1;
}
return 0;
}
if(arr[i][j]){
ans[i][j]=1;
if(rat(i,j+1,n,m,arr,ans)){
return 1;
}
if(rat(i+1,j,n,m,arr,ans)){
return 1;
}
if(rat(i,j-1,n,m,arr,ans)){
return 1;
}
if(rat(i-1,j,n,m,arr,ans)){
return 1;
}
ans[i][j]=0;
}
return 0;
}
int main(){
int n,m;cin>>n>>m;
int **arr=new int*[n];
int **ans=new int*[n];
for(int i=0;i<n;i++){
arr[i]=new int[m];
ans[i]=new int[m];
for(int j=0;j<m;j++){
cin>>arr[i][j];
ans[i][j]=0;
}
}
if(rat(0,0,n,m,arr,ans)){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Not possible";
}}

4.
#include<bits/stdc++.h>

using namespace std;


bool isSafe(int x,int y,int n,int m,int **arr){
for(int i=y;i>-1;i--){
if(arr[i][x]){
return 0;
}
}
for(int i=y,j=x;i>-1 && j>-1;i--,j--){
if(arr[i][j]){
return 0;
}
}
for(int i=y,j=x;i>-1 && j<m;i--,j++){
if(arr[i][j]){
return 0;
}
}
return 1;
}
bool nQueen(int x,int y,int n,int m,int **arr){
if(y>=n){
return 1;
}
for(int j=0;j<m;j++){
if(isSafe(j,y,n,m,arr)){

arr[y][j]=1;

if(nQueen(x,y+1,n,m,arr)){
return 1;
}

arr[y][j]=0;
}
}
return 0;
}

int main(){
int n,m;cin>>n>>m;
int **arr=new int*[n];
for(int i=0;i<n;i++){
arr[i]=new int[m];
for(int j=0;j<m;j++){
arr[i][j]=0;
}
}
if(nQueen(0,0,n,m,arr)){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"Not possible";
}
}

WEEK-9 A&B

ANS-1

#include<iostream>

#include<queue>

using namespace std;

struct node{

int data;

node*down;

node*next;

};

node *createList(int *arr, int n)


{

node *head=NULL;

node *p;

int i;

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

if (head==NULL){

head=p=new node();

else

p->next = new node();

p = p->next;

p->data=arr[i];

p->next=p->down=NULL;

return head;

node *createList(void)

int arr1[]={10, 5, 12, 7, 11};

int arr2[]={4, 20, 13};

int arr3[]={17, 6};

int arr4[]={9, 8};

int arr5[]={19, 15};

int arr6[]={2};

int arr7[]={16};

int arr8[]={3};

node *head1 = createList(arr1,5);

node *head2 = createList(arr2,3);


node *head3 = createList(arr3,2);

node *head4 = createList(arr4,2);

node *head5 = createList(arr5,2);

node *head6 = createList(arr6,1);

node *head7 = createList(arr7,1);

node *head8 = createList(arr8,1);

head1->down = head2;

head1->next->next->next->down= head3;

head3->down = head4;

head4->down = head5;

head2->next->down = head6;

head2->next->next->down= head7;

head7->down = head8;

return head1;

class MultiLinkedList{

public:

node*head;

MultiLinkedList(){

head=NULL;

void createTree(node*head1){

head=head1;

void Display(node*curr){

queue<node*>q;

q.push(curr);

while(!q.empty()){

curr=q.front();

while(curr!=NULL){

if(curr->down!=NULL){
q.push(curr->down);

cout<<curr->data<<"->";

curr=curr->next;

q.pop();

};

int main(){

node *head=NULL;

head=createList();

MultiLinkedList m;

m.createTree(head);

m.Display(m.head);

return 0;

ANS-2

#include <iostream>

using namespace std;

class TreeNode {

public:

int data;

TreeNode* left;
TreeNode* right;

TreeNode(int val) : data(val), left(NULL), right(NULL) {}

};

class BinaryTree {

private:

TreeNode* root;

TreeNode* insertRecursive(TreeNode* node, int val) {

if (node == NULL)

return new TreeNode(val);

if (val <= node->data) {

node->left = insertRecursive(node->left, val);

} else {

node->right = insertRecursive(node->right, val);

return node;

int getHeightRecursive(TreeNode* node) {

if (node == NULL)

return 0;

int leftHeight = getHeightRecursive(node->left);


int rightHeight = getHeightRecursive(node->right);

return 1 + max(leftHeight, rightHeight);

bool hasDuplicatesRecursive(TreeNode* node, int val) {

if (node == NULL)

return false;

if (val == node->data)

return true;

if (val < node->data)

return hasDuplicatesRecursive(node->left, val);

else

return hasDuplicatesRecursive(node->right, val);

public:

BinaryTree() : root(NULL) {}

void insertRecursive(int val) {

root = insertRecursive(root, val);

int getHeight() {

return getHeightRecursive(root);
}

bool hasDuplicates(int val) {

return hasDuplicatesRecursive(root, val);

};

int main() {

BinaryTree tree;

tree.insertRecursive(10);

tree.insertRecursive(5);

tree.insertRecursive(15);

tree.insertRecursive(3);

tree.insertRecursive(7);

cout << "Height of the tree: " << tree.getHeight() << endl;

bool hasDupes = tree.hasDuplicates(5);

cout << "Tree has duplicate values: " << (hasDupes ? "Yes" : "No") << endl;

return 0;

#include <iostream>

using namespace std;

class TreeNode {
public:

int data;

TreeNode* left;

TreeNode* right;

TreeNode(int val) : data(val), left(NULL), right(NULL) {}

};

class BinaryTree {

private:

TreeNode* root;

TreeNode* insertRecursive(TreeNode* node, int val) {

if (node == NULL)

return new TreeNode(val);

if (val <= node->data) {

node->left = insertRecursive(node->left, val);

} else {

node->right = insertRecursive(node->right, val);

return node;

void displayinorder(TreeNode* root)

{
if(root != NULL)

displayinorder(root->left);

cout<<root->data<<" ";

displayinorder(root->right);

void deleteinorder(TreeNode* root,int val)

if(root != NULL)

deleteinorder(root->left,val);

if(val==root->data)

delete root;

deleteinorder(root->right,val);

public:

BinaryTree() : root(NULL) {}

void insertRecursive(int val) {

root = insertRecursive(root, val);

}
void display()

displayinorder(root);

cout << endl;

void deletenode(int val)

deleteinorder(root,val);

cout << val<< " has been deleted";

};

int main() {

BinaryTree tree;

tree.insertRecursive(10);

tree.insertRecursive(5);

tree.insertRecursive(15);

tree.insertRecursive(3);

tree.insertRecursive(7);

tree.insertRecursive(16);

tree.insertRecursive(9);

tree.insertRecursive(1);

tree.insertRecursive(4);

tree.insertRecursive(6);

tree.insertRecursive(2);
tree.insertRecursive(8);

tree.insertRecursive(11);

tree.insertRecursive(17);

tree.insertRecursive(13);

tree.display();

tree.deletenode(1);

tree.display();

return 0;

ANS-3

abcd^e-fgh*+^*+i-

—------------------------------------------------------------------------------------

WEEK-10 A

ANS-1

1.

#include <iostream>

const int table_size = 10;

int hash_table[table_size];

void initializeHashTable() {
for (int i = 0; i < table_size; i++) {

hash_table[i] = -1;

int hashFunction(int key) {

return key % 9;

int linearProbing(int key, int i) {

return (key + i) % table_size;

void insertKey(int key) {

int index = hashFunction(key);

int i = 0;

while (hash_table[index] != -1) {

i++;

index = linearProbing(index, i);

hash_table[index] = key;

int main() {

initializeHashTable();
int keys[] = {14, 18, 24, 20, 3, 23, 33, 15};

int len=sizeof(keys)/sizeof(0);

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

insertKey(keys[i]);

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

std::cout << "Index " << i << ": " << hash_table[i] << std::endl;

return 0;

ANS-2

#include <iostream>

using namespace std;

const int table_size = 7;


int hash_table[table_size];

void initializeHashTable() {

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

hash_table[i] = -1;

int hashFunction(int key) {

return key % 7;

int linearProbing(int key, int i) {

return (key + i) % table_size;

void insertKey(int key) {

int index = hashFunction(key);

int i = 0;

while (hash_table[index] != -1) {

i++;

index = linearProbing(index, i);

if (i >= table_size) {

cout << "Hash table is full. Cannot insert " << key << endl;

return;

}
}

hash_table[index] = key;

int main() {

initializeHashTable();

int keys[] = {50, 700, 76, 85, 92, 73, 101, 70};

int len = sizeof(keys) / sizeof(keys[0]);

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

insertKey(keys[i]);

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

cout << "Index " << i << ": " << hash_table[i] << endl;

return 0;

}
ANS-3

#include <iostream>

#include <vector>

using namespace std;

struct KeyValuePair {

int key;

int value;

KeyValuePair* next;

};

int hashFunction(int key, int numBuckets) {

return key % numBuckets;

int main() {
int numBuckets;

cout << "Enter the number of buckets: ";

cin >> numBuckets;

vector<KeyValuePair*> hashTable(numBuckets, NULL);

char choice;

do {

int key, value;

cout << "Enter a key: ";

cin >> key;

cout << "Enter a value: ";

cin >> value;

int hashKey = hashFunction(key, numBuckets);

KeyValuePair* kvp = new KeyValuePair{key, value, NULL};

if (!hashTable[hashKey]) {

hashTable[hashKey] = kvp;

} else {

kvp->next = hashTable[hashKey];

hashTable[hashKey] = kvp;

}
cout << "Do you want to enter more values? (y/n): ";

cin >> choice;

} while (choice == 'y' || choice == 'Y');

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

cout << "Bucket " << i << ": ";

KeyValuePair* current = hashTable[i];

while (current) {

cout << "(" << current->key << ", " << current->value << ") ";

current = current->next;

cout << endl;

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

KeyValuePair* current = hashTable[i];

while (current) {

KeyValuePair* next = current->next;

delete current;

current = next;

return 0;

}
ANS-4

#include <iostream>

using namespace std;

const int table_size = 10;

int hash_table[table_size];

void initializeHashTable() {

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

hash_table[i] = -1;

int hashFunction1(int key) {

return key % 7;
}

int hashFunction2(int key) {

return key % 3;

int doubleHashing(int key, int i) {

return (hashFunction1(key) + i * hashFunction2(key)) % table_size;

void insertKey(int key) {

int index = hashFunction1(key);

int i = 0;

while (hash_table[index] != -1) {

i++;

index = doubleHashing(key, i);

hash_table[index] = key;

int main() {

initializeHashTable();

int keys[] = {50, 700, 76, 85, 92, 73, 101, 70};

int len = sizeof(keys) / sizeof(keys[0]);


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

insertKey(keys[i]);

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

cout << "Index " << i << ": " << hash_table[i] << endl;

return 0;

ANS-5

#include <iostream>

#include <vector>

using namespace std;


pair<int, int> largestSquareArea(const vector<int>& arr) {

vector<int> sortedArr = arr;

int n = sortedArr.size();

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

for (int j = 0; j < n - i - 1; j++) {

if (sortedArr[j] > sortedArr[j + 1]) {

swap(sortedArr[j], sortedArr[j + 1]);

int max_height = sortedArr[n - 1];

int count = 0;

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

if (sortedArr[i] == max_height) {

count++;

int area = max_height * max_height;

return make_pair(area, count);

int main() {
int arr[] = {5, 3, 2, 3, 6, 3, 3};

int arr_size = sizeof(arr) / sizeof(arr[0]);

vector<int> arr_vector(arr, arr + arr_size);

pair<int, int> result = largestSquareArea(arr_vector);

cout << "Area = " << result.first << endl;

cout << "Count = " << result.second << endl;

return 0;

WEEK-10 B

ANS-1

#include<iostream>

#include<queue>

using namespace std;

class node{

public:
int data;

node*left;

node*right;

node(int value){

data=value;

left=NULL;

right=NULL;

};

class LevelTree{

public:

node*root;

LevelTree(){

root=NULL;

void createTree(int arr[],int n){

queue<node*>q;

int index=0;

root=new node(arr[index]);

index++;

q.push(root);

while(!q.empty()&&index<n){

node*curr=q.front();

q.pop();

if(arr[index]!=0){

curr->left=new node(arr[index]);

q.push(curr->left);

index++;

if(arr[index]!=0){

curr->right=new node(arr[index]);
q.push(curr->right);

index++;

void Preorder(node*curr){

if(curr==NULL){

return;

cout<<curr->data<<" ";

Preorder(curr->left);

Preorder(curr->right);

void Inorder(node*curr){

if(curr==NULL){

return;

Inorder(curr->left);

cout<<curr->data<<" ";

Inorder(curr->right);

void Postorder(node*curr){

if(curr==NULL){

return;

Postorder(curr->left);

Postorder(curr->right);

cout<<curr->data<<" ";

void levelorder(node*curr){

queue<node*>q;
q.push(curr);

while(!q.empty()){

node*temp=q.front();

q.pop();

cout<<temp->data<<" ";

if(temp->left){

q.push(temp->left);

if(temp->right){

q.push(temp->right);

};

int main(){

int arr[]={1,2,3,4,5,6,7,0,8,9,0,0,0,10,11,12,13,0,14,15,0,16,17};

int n=sizeof(arr)/sizeof(arr[0]);

LevelTree t;

t.createTree(arr,n);

cout<<"Pre-order:";

t.Preorder(t.root);

cout<<endl;

cout<<"In-order:";

t.Inorder(t.root);

cout<<endl;

cout<<"Post-order:";

t.Postorder(t.root);

cout<<endl;

cout<<"Level-order:";

t.levelorder(t.root);

}
ANS-2

#include<iostream>

#include<queue>

using namespace std;

class node{

public:

int data;

node*left;

node*right;

node(int value){

data=value;

left=NULL;

right=NULL;

};

class LevelTree{

public:

node*root;

LevelTree(){

root=NULL;

void createTree(int arr[],int n){

queue<node*>q;
int index=0;

root=new node(arr[index]);

index++;

q.push(root);

while(!q.empty()&&index<n){

node*curr=q.front();

q.pop();

if(arr[index]!=0){

curr->left=new node(arr[index]);

q.push(curr->left);

index++;

if(arr[index]!=0){

curr->right=new node(arr[index]);

q.push(curr->right);

index++;

int findMaxPath(node*curr){

if(curr==NULL) {

return 0;

int leftSum=findMaxPath(curr->left);

int rightSum=findMaxPath(curr->right);

return max(leftSum,rightSum)+curr->data;

int maxPath(){

if (root==NULL){

return 0;

}
int result=findMaxPath(root);

return result;

};

int main(){

int arr[]={1,2,3,4,5,6,7,0,8,9,0,0,0,10,11,12,13,0,14,15,0,16,17};

int n=sizeof(arr)/sizeof(arr[0]);

LevelTree t;

t.createTree(arr,n);

int maxSum=t.maxPath();

cout<<"Maximum Sum Path from Root to Leaf:"<<maxSum<<endl;

ANS-3

#include <iostream>

#include <queue>

#include <stack>

using namespace std;

class TreeNode {

public:

char data;

TreeNode* left;

TreeNode* right;

TreeNode(char value) : data(value), left(NULL), right(NULL) {}

};
void levelOrderTraversal(TreeNode* root) {

if (!root) {

return;

queue<TreeNode*> q;

q.push(root);

while (!q.empty()) {

TreeNode* current = q.front();

cout << current->data << " ";

q.pop();

if (current->left) {

q.push(current->left);

if (current->right) {

q.push(current->right);

void spiralOrderTraversal(TreeNode* root) {

if (!root) {

return;

stack<TreeNode*> s1;

stack<TreeNode*> s2;
bool leftToRight = true;

s1.push(root);

while (!s1.empty() || !s2.empty()) {

while (!s1.empty()) {

TreeNode* current = s1.top();

s1.pop();

cout << current->data << " ";

if (leftToRight) {

if (current->left) {

s2.push(current->left);

if (current->right) {

s2.push(current->right);

} else {

if (current->right) {

s2.push(current->right);

if (current->left) {

s2.push(current->left);

swap(s1, s2);

leftToRight = !leftToRight;

}
int height(TreeNode* root) {

if (!root) {

return 0;

int leftHeight = height(root->left);

int rightHeight = height(root->right);

return max(leftHeight, rightHeight) + 1;

void printGivenLevel(TreeNode* root, int level) {

if (!root) {

return;

if (level == 1) {

cout << root->data << " ";

} else if (level > 1) {

printGivenLevel(root->left, level - 1);

printGivenLevel(root->right, level - 1);

void recursiveLevelOrderTraversal(TreeNode* root) {

int h = height(root);

for (int i = 1; i <= h; i++) {

printGivenLevel(root, i);

}
}

void printGivenLevelReverse(TreeNode* root, int level) {

if (!root) {

return;

if (level == 1) {

cout << root->data << " ";

} else if (level > 1) {

printGivenLevelReverse(root->right, level - 1);

printGivenLevelReverse(root->left, level - 1);

void recursiveSpiralOrderTraversal(TreeNode* root) {

int h = height(root);

bool leftToRight = true;

for (int i = 1; i <= h; i++) {

if (leftToRight) {

printGivenLevel(root, i);

} else {

printGivenLevelReverse(root, i);

leftToRight = !leftToRight;

int main() {

TreeNode* root = new TreeNode('A');


root->left = new TreeNode('B');

root->right = new TreeNode('C');

root->left->left = new TreeNode('D');

root->left->right = new TreeNode('E');

root->right->left = new TreeNode('F');

root->right->right = new TreeNode('G');

root->left->left->left = new TreeNode('H');

root->left->left->right = new TreeNode('I');

cout << "Non-Recursive Level-Order Traversal: ";

levelOrderTraversal(root);

cout << endl;

cout << "Non-Recursive Spiral-Order Traversal: ";

spiralOrderTraversal(root);

cout << endl;

cout << "Recursive Level-Order Traversal: ";

recursiveLevelOrderTraversal(root);

cout << endl;

cout << "Recursive Spiral-Order Traversal: ";

recursiveSpiralOrderTraversal(root);

cout << endl;

return 0;

}
ANS-4

#include <iostream>

using namespace std;

class TreeNode {

public:

int data;

int count;

TreeNode* left;

TreeNode* right;

TreeNode(int value) : data(value), count(1), left(nullptr), right(nullptr) {}

};

class ModifiedBST {

public:

TreeNode* root;

ModifiedBST() {

root = nullptr;

TreeNode* insert(TreeNode* node, int key) {

if (node == nullptr) {
return new TreeNode(key);

if (key == node->data) {

node->count++;

} else if (key < node->data) {

node->left = insert(node->left, key);

} else {

node->right = insert(node->right, key);

return node;

void insertElement(int key) {

root = insert(root, key);

void inOrderTraversal(TreeNode* node) {

if (node == nullptr) {

return;

inOrderTraversal(node->left);

for (int i = 0; i < node->count; i++) {

cout << node->data << " ";

inOrderTraversal(node->right);

}
void displayInOrder() {

cout << "In-order traversal: ";

inOrderTraversal(root);

cout << endl;

TreeNode* findMin(TreeNode* node) {

while (node->left) {

node = node->left;

return node;

TreeNode* deleteNode(TreeNode* node, int key) {

if (node == nullptr) {

return node;

if (key < node->data) {

node->left = deleteNode(node->left, key);

} else if (key > node->data) {

node->right = deleteNode(node->right, key);

} else {

if (node->count > 1) {

node->count--;

} else {

if (node->left == nullptr) {

TreeNode* temp = node->right;

delete node;

return temp;
} else if (node->right == nullptr) {

TreeNode* temp = node->left;

delete node;

return temp;

TreeNode* temp = findMin(node->right);

node->data = temp->data;

node->count = temp->count;

node->right = deleteNode(node->right, temp->data);

return node;

void deleteElement(int key) {

root = deleteNode(root, key);

};

int main() {

ModifiedBST bst;

int elements[] = {10, 20, 30, 40, 50, 40, 35, 25, 20, 40, 18, 19, 22, 27, 30, 27};

int n = sizeof(elements) / sizeof(elements[0]);

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

bst.insertElement(elements[i]);

}
bst.displayInOrder();

int elementToDelete;

cout << "Enter an element to delete: ";

cin >> elementToDelete;

bst.deleteElement(elementToDelete);

bst.displayInOrder();

return 0;

—----------------------------------------------------------------------------------------------------------------------------

WEEK-11 B

ANS-1

#include <iostream>

using namespace std;

enum Color { RED, BLACK };

class Node {

public:

int data;

Color color;
Node* parent;

Node* left;

Node* right;

Node(int val) : data(val), color(RED), parent(nullptr), left(nullptr), right(nullptr) {}

};

class RBTree {

private:

Node* root;

Node* TNULL;

void preOrderHelper(Node* node) {

if (node != TNULL) {

cout << node->data << " ";

preOrderHelper(node->left);

preOrderHelper(node->right);

void inOrderHelper(Node* node) {

if (node != TNULL) {

inOrderHelper(node->left);

cout << node->data << " ";

inOrderHelper(node->right);

Node* searchTreeHelper(Node* node, int key) {

if (node == TNULL || key == node->data) {

return node;
}

if (key < node->data) {

return searchTreeHelper(node->left, key);

return searchTreeHelper(node->right, key);

void fixInsert(Node* k) {

Node* u;

while (k->parent->color == RED) {

if (k->parent == k->parent->parent->right) {

u = k->parent->parent->left;

if (u->color == RED) {

u->color = BLACK;

k->parent->color = BLACK;

k->parent->parent->color = RED;

k = k->parent->parent;

} else {

if (k == k->parent->left) {

k = k->parent;

rightRotate(k);

k->parent->color = BLACK;

k->parent->parent->color = RED;

leftRotate(k->parent->parent);

} else {

u = k->parent->parent->right;
if (u->color == RED) {

u->color = BLACK;

k->parent->color = BLACK;

k->parent->parent->color = RED;

k = k->parent->parent;

} else {

if (k == k->parent->right) {

k = k->parent;

leftRotate(k);

k->parent->color = BLACK;

k->parent->parent->color = RED;

rightRotate(k->parent->parent);

if (k == root) {

break;

root->color = BLACK;

void rbTransplant(Node* u, Node* v) {

if (u->parent == nullptr) {

root = v;

} else if (u == u->parent->left) {

u->parent->left = v;

} else {

u->parent->right = v;

v->parent = u->parent;
}

void fixDelete(Node* x) {

Node* s;

while (x != root && x->color == BLACK) {

if (x == x->parent->left) {

s = x->parent->right;

if (s->color == RED) {

s->color = BLACK;

x->parent->color = RED;

leftRotate(x->parent);

s = x->parent->right;

if (s->left->color == BLACK && s->right->color == BLACK) {

s->color = RED;

x = x->parent;

} else {

if (s->right->color == BLACK) {

s->left->color = BLACK;

s->color = RED;

rightRotate(s);

s = x->parent->right;

s->color = x->parent->color;

x->parent->color = BLACK;

s->right->color = BLACK;

leftRotate(x->parent);

x = root;

} else {
s = x->parent->left;

if (s->color == RED) {

s->color = BLACK;

x->parent->color = RED;

rightRotate(x->parent);

s = x->parent->left;

if (s->right->color == BLACK && s->right->color == BLACK) {

s->color = RED;

x = x->parent;

} else {

if (s->left->color == BLACK) {

s->right->color = BLACK;

s->color = RED;

leftRotate(s);

s = x->parent->left;

s->color = x->parent->color;

x->parent->color = BLACK;

s->left->color = BLACK;

rightRotate(x->parent);

x = root;

x->color = BLACK;

void rbDeleteNodeHelper(Node* node, int key) {

Node* z = TNULL;
Node* x, y;

while (node != TNULL) {

if (node->data == key) {

z = node;

if (node->data <= key) {

node = node->right;

} else {

node = node->left;

if (z == TNULL) {

cout << "Key not found in the tree" << endl;

return;

y = z;

Color yOriginalColor = y->color;

if (z->left == TNULL) {

x = z->right;

rbTransplant(z, z->right);

} else if (z->right == TNULL) {

x = z->left;

rbTransplant(z, z->left);

} else {

y = minimum(z->right);

yOriginalColor = y->color;

x = y->right;

if (y->parent == z) {
x->parent = y;

} else {

rbTransplant(y, y->right);

y->right = z->right;

y->right->parent = y;

rbTransplant(z, y);

y->left = z->left;

y->left->parent = y;

y->color = z->color;

if (yOriginalColor == BLACK) {

fixDelete(x);

// Preorder

// Inorder

// Post order

// Search

// Insert

// Delete

// Find min

// Find max

public:

RBTree() {

TNULL = new Node(0);

TNULL->color = BLACK;

TNULL->left = nullptr;

TNULL->right = nullptr;
root = TNULL;

// Preorder

void preOrder() {

preOrderHelper

ANS-2

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

using namespace std;

enum Color { RED, BLACK };

class Node {

public:

string data;

Color color;

Node* parent;

Node* left;

Node* right;

Node(const string& word) : data(word), color(RED), parent(nullptr), left(nullptr), right(nullptr) {}

};

class SpellChecker {

private:

Node* root;

Node* TNULL;
void leftRotate(Node* x) {

Node* y = x->right;

x->right = y->left;

if (y->left != TNULL) {

y->left->parent = x;

y->parent = x->parent;

if (x->parent == nullptr) {

root = y;

} else if (x == x->parent->left) {

x->parent->left = y;

} else {

x->parent->right = y;

y->left = x;

x->parent = y;

void rightRotate(Node* x) {

Node* y = x->left;

x->left = y->right;

if (y->right != TNULL) {

y->right->parent = x;

y->parent = x->parent;

if (x->parent == nullptr) {

root = y;

} else if (x == x->parent->right) {

x->parent->right = y;

} else {
x->parent->left = y;

y->right = x;

x->parent = y;

void fixInsert(Node* k) {

Node* u;

while (k->parent->color == RED) {

if (k->parent == k->parent->parent->right) {

u = k->parent->parent->left;

if (u->color == RED) {

u->color = BLACK;

k->parent->color = BLACK;

k->parent->parent->color = RED;

k = k->parent->parent;

} else {

if (k == k->parent->left) {

k = k->parent;

rightRotate(k);

k->parent->color = BLACK;

k->parent->parent->color = RED;

leftRotate(k->parent->parent);

} else {

u = k->parent->parent->right;

if (u->color == RED) {

u->color = BLACK;

k->parent->color = BLACK;

k->parent->parent->color = RED;
k = k->parent->parent;

} else {

if (k == k->parent->right) {

k = k->parent;

leftRotate(k);

k->parent->color = BLACK;

k->parent->parent->color = RED;

rightRotate(k->parent->parent);

if (k == root) {

break;

root->color = BLACK;

Node* searchTreeHelper(Node* node, const string& word) {

if (node == TNULL || word == node->data) {

return node;

if (word < node->data) {

return searchTreeHelper(node->left, word);

return searchTreeHelper(node->right, word);

public:
SpellChecker() {

TNULL = new Node("");

TNULL->color = BLACK;

TNULL->left = nullptr;

TNULL->right = nullptr;

root = TNULL;

void insert(const string& word) {

Node* node = new Node(word);

Node* y = nullptr;

Node* x = root;

while (x != TNULL) {

y = x;

if (node->data < x->data) {

x = x->left;

} else {

x = x->right;

node->parent = y;

if (y == nullptr) {

root = node;

} else if (node->data < y->data) {

y->left = node;

} else {

y->right = node;

}
if (node->parent == nullptr) {

node->color = BLACK;

return;

if (node->parent->parent == nullptr) {

return;

fixInsert(node);

bool search(const string& word) {

Node* node = searchTreeHelper(root, word);

return (node != TNULL);

void tokenizeAndCheck(const string& text) {

string word = "";

vector<string> words;

for (char c : text) {

if (isalpha(c)) {

word += tolower(c);

} else if (!word.empty()) {

if (!search(word)) {

cout << "Potential misspelling: " << word << endl;

word = "";

}
if (!word.empty() && !search(word)) {

cout << "Potential misspelling: " << word << endl;

void inOrder() {

inOrderHelper(root);

cout << endl;

void inOrderHelper(Node* node) {

if (node != TNULL) {

inOrderHelper(node->left);

cout << node->data << " ";

inOrderHelper(node->right);

};

int main() {

SpellChecker checker;

// Insert valid words into the dictionary

checker.insert("apple");

checker.insert("banana");

checker.insert("cherry");

checker.insert("date");

checker.insert("elderberry");

// Check a sample text for misspellings


string text = "Apples are delicious, but bananna and chery are not elderbery.";

checker.tokenizeAndCheck(text);

// Display the dictionary (valid words)

cout << "Dictionary: ";

checker.inOrder();

return 0;

ANS-3

#include <iostream>

using namespace std;

enum Color { RED, BLACK };

class Node {

public:

int data;

Color color;

Node* parent;

Node* left;

Node* right;

int size; // Size of the subtree rooted at this node

Node(int val) : data(val), color(RED), parent(nullptr), left(nullptr), right(nullptr), size(1) {}

};

class DynamicOrderStatistics {

private:

Node* root;
Node* TNULL;

void leftRotate(Node* x) {

Node* y = x->right;

x->right = y->left;

if (y->left != TNULL) {

y->left->parent = x;

y->parent = x->parent;

if (x->parent == nullptr) {

root = y;

} else if (x == x->parent->left) {

x->parent->left = y;

} else {

x->parent->right = y;

y->left = x;

x->parent = y;

y->size = x->size;

x->size = x->left->size + x->right->size + 1;

void rightRotate(Node* x) {

Node* y = x->left;

x->left = y->right;

if (y->right != TNULL) {

y->right->parent = x;

y->parent = x->parent;

if (x->parent == nullptr) {

root = y;
} else if (x == x->parent->right) {

x->parent->right = y;

} else {

x->parent->left = y;

y->right = x;

x->parent = y;

y->size = x->size;

x->size = x->left->size + x->right->size + 1;

void fixInsert(Node* k) {

Node* u;

while (k->parent->color == RED) {

if (k->parent == k->parent->parent->right) {

u = k->parent->parent->left;

if (u->color == RED) {

u->color = BLACK;

k->parent->color = BLACK;

k->parent->parent->color = RED;

k = k->parent->parent;

} else {

if (k == k->parent->left) {

k = k->parent;

rightRotate(k);

k->parent->color = BLACK;

k->parent->parent->color = RED;

leftRotate(k->parent->parent);

} else {
u = k->parent->parent->right;

if (u->color == RED) {

u->color = BLACK;

k->parent->color = BLACK;

k->parent->parent->color = RED;

k = k->parent->parent;

} else {

if (k == k->parent->right) {

k = k->parent;

leftRotate(k);

k->parent->color = BLACK;

k->parent->parent->color = RED;

rightRotate(k->parent->parent);

if (k == root) {

break;

root->color = BLACK;

void rbTransplant(Node* u, Node* v) {

if (u->parent == nullptr) {

root = v;

} else if (u == u->parent->left) {

u->parent->left = v;

} else {

u->parent->right = v;

}
v->parent = u->parent;

void fixDelete(Node* x) {

Node* s;

while (x != root && x->color == BLACK) {

if (x == x->parent->left) {

s = x->parent->right;

if (s->color == RED) {

s->color = BLACK;

x->parent->color = RED;

leftRotate(x->parent);

s = x->parent->right;

if (s->left->color == BLACK && s->right->color == BLACK) {

s->color = RED;

x = x->parent;

} else {

if (s->right->color == BLACK) {

s->left->color = BLACK;

s->color = RED;

rightRotate(s);

s = x->parent->right;

s->color = x->parent->color;

x->parent->color = BLACK;

s->right->color = BLACK;

leftRotate(x->parent);

x = root;

}
} else {

s = x->parent->left;

if (s->color == RED) {

s->color = BLACK;

x->parent->color = RED;

rightRotate(x->parent);

s = x->parent->left;

if (s->right->color == BLACK && s->right->color == BLACK) {

s->color = RED;

x = x->parent;

} else {

if (s->left->color == BLACK) {

s->right->color = BLACK;

s->color = RED;

leftRotate(s);

s = x->parent->left;

s->color = x->parent->color;

x->parent->color = BLACK;

s->left->color = BLACK;

rightRotate(x->parent);

x = root;

x->color = BLACK;

void rbDeleteNodeHelper(Node* node, int key) {


Node* z = TNULL;

Node* x, y;

while (node != TNULL) {

if (node->data == key) {

z = node;

if (node->data <= key) {

node = node->right;

} else {

node = node->left;

if (z == TNULL) {

cout << "Key not found in the tree" << endl;

return;

y = z;

Color yOriginalColor = y->color;

if (z->left == TNULL) {

x = z->right;

rbTransplant(z, z->right);

} else if (z->right == TNULL) {

x = z->left;

rbTransplant(z, z->left);

} else {

y = minimum(z->right);

yOriginalColor = y->color;

x = y->right;
if (y->parent == z) {

x->parent = y;

} else {

rbTransplant(y, y->right);

y->right = z->right;

y->right->parent = y;

rbTransplant(z, y);

y->left = z->left;

y->left->parent = y;

y->color = z->color;

if (yOriginalColor == BLACK) {

fixDelete(x);

Node* minimum(Node* node) {

while (node->left != TNULL) {

node = node->left;

return node;

int rankHelper(Node* node, int x) {

if (node == TNULL) {

return 0;

if (x == node->data) {

return node->left->size + 1;

}
if (x < node->data) {

return rankHelper(node->left, x);

return rankHelper(node->right, x) + node->left->size + 1;

public:

DynamicOrderStatistics() {

TNULL = new Node(0);

TNULL->color = BLACK;

TNULL->left = nullptr;

TNULL->right = nullptr;

root = TNULL;

void insert(int x) {

Node* node = new Node(x);

Node* y = nullptr;

Node* xNode = root;

while (xNode != TNULL) {

y = xNode;

if (node->data < xNode->data) {

xNode->size++;

xNode = xNode->left;

} else {

xNode->size++;

xNode = xNode->right;

}
node->parent = y;

if (y == nullptr) {

root = node;

} else if (node->data < y->data) {

y->left = node;

} else {

y->right = node;

if (node->parent == nullptr) {

node->color = BLACK;

return;

if (node->parent->parent == nullptr) {

return;

fixInsert(node);

void remove(int key) {

rbDeleteNodeHelper(root, key);

int select(int k) {

Node* current = root;

while (current != TNULL) {

if (current->left->size + 1 == k) {

return current->data;

} else if (k <= current->left->size) {


current = current->left;

} else {

k -= current->left->size + 1;

current = current->right;

return -1; // Element not found

int rank(int x) {

return rankHelper(root, x);

// Inorder traversal to verify the tree

void inOrder() {

inOrderHelper(root);

cout << endl;

void inOrderHelper(Node* node) {

if (node != TNULL) {

inOrderHelper(node->left);

cout << node->data << " ";

inOrderHelper(node->right);

};

int main() {

DynamicOrderStatistics tree;
tree.insert(20);

tree.insert(30);

tree.insert(40);

tree.insert(50);

tree.insert(60);

tree.insert(70);

tree.insert(80);

tree.insert(90);

tree.insert(100);

tree.insert(110);

tree.insert(120);

tree.insert(130);

tree.inOrder(); // Inorder traversal to verify the tree

cout << "Rank of 70: " << tree.rank(70) << endl; // Should print 6

tree.remove(130);

tree.remove(80);

tree.remove(60);

tree.remove(20);

tree.remove(100);

tree.remove(60);

tree.remove(110);

tree.remove(70);

tree.remove(30);

tree.remove(120);

tree.inOrder(); // Inorder traversal after deletions

cout << "Select 7: " << tree.select(7) << endl; // Should print 110
return 0;

WEEK-11 A

ANS-1

#include <iostream>

#include <stack>

#include <queue>

class TreeNode {

public:

int data;

TreeNode* left;

TreeNode* right;

TreeNode(int value) : data(value), left(NULL), right(NULL) {}

};

TreeNode* insert(TreeNode* root, int value) {

if (root == NULL) {

return new TreeNode(value);

if (value < root->data) {

root->left = insert(root->left, value);

} else {

root->right = insert(root->right, value);

}
return root;

int getHeightRecursive(TreeNode* root) {

if (root == NULL) {

return 0;

int leftHeight = getHeightRecursive(root->left);

int rightHeight = getHeightRecursive(root->right);

return 1 + std::max(leftHeight, rightHeight);

void inorderTraversal(TreeNode* root) {

if (root == NULL) return;

std::stack<TreeNode*> s;

TreeNode* current = root;

while (current != NULL || !s.empty()) {

while (current != NULL) {

s.push(current);

current = current->left;

current = s.top();

s.pop();

std::cout << current->data << " ";

current = current->right;

}
void preorderTraversal(TreeNode* root) {

if (root == NULL) return;

std::stack<TreeNode*> s;

s.push(root);

while (!s.empty()) {

TreeNode* current = s.top();

s.pop();

std::cout << current->data << " ";

if (current->right) s.push(current->right);

if (current->left) s.push(current->left);

void postorderTraversal(TreeNode* root) {

if (root == NULL) return;

std::stack<TreeNode*> s1, s2;

s1.push(root);

while (!s1.empty()) {

TreeNode* current = s1.top();

s1.pop();

s2.push(current);

if (current->left) s1.push(current->left);

if (current->right) s1.push(current->right);

}
while (!s2.empty()) {

TreeNode* current = s2.top();

s2.pop();

std::cout << current->data << " ";

void levelOrderTraversal(TreeNode* root) {

if (root == NULL) return;

std::queue<TreeNode*> q;

q.push(root);

while (!q.empty()) {

TreeNode* current = q.front();

q.pop();

std::cout << current->data << " ";

if (current->left) q.push(current->left);

if (current->right) q.push(current->right);

int main() {

TreeNode* root = NULL;

int values[] = {10, 20, 30, 40, 50, 60, 70, 75, 80};

int numValues = sizeof(values) / sizeof(values[0]);

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


root = insert(root, values[i]);

std::cout << "Height of the tree (recursive): " << getHeightRecursive(root) << std::endl;

std::cout << "Inorder Traversal (non-recursive): ";

inorderTraversal(root);

std::cout << std::endl;

std::cout << "Preorder Traversal (non-recursive): ";

preorderTraversal(root);

std::cout << std::endl;

std::cout << "Postorder Traversal (non-recursive): ";

postorderTraversal(root);

std::cout << std::endl;

std::cout << "Level Order Traversal (non-recursive): ";

levelOrderTraversal(root);

std::cout << std::endl;

return 0;
ANS-2

#include <iostream>

#include <vector>

class TreeNode {

public:

int data;

TreeNode* left;

TreeNode* right;

TreeNode(int value) : data(value), left(NULL), right(NULL) {}

};

TreeNode* insert(TreeNode* root, int value) {

if (root == NULL) {

return new TreeNode(value);

if (value < root->data) {

root->left = insert(root->left, value);

} else {

root->right = insert(root->right, value);

return root;

int getHeightRecursive(TreeNode* root) {


if (root == NULL) {

return 0;

int leftHeight = getHeightRecursive(root->left);

int rightHeight = getHeightRecursive(root->right);

return 1 + std::max(leftHeight, rightHeight);

TreeNode* createBalancedBST(std::vector<int>&amp; sortedArray, int start, int end) {

if (start > end) {

return NULL;

int mid = (start + end) / 2;

TreeNode* root = new TreeNode(sortedArray[mid]);

root->left = createBalancedBST(sortedArray, start, mid - 1);

root->right = createBalancedBST(sortedArray, mid + 1, end);

return root;

// Function to perform insertion sort

void insertionSort(std::vector<int>&amp; arr) {

int n = arr.size();

for (int i = 1; i < n; i++) {

int key = arr[i];

int j = i - 1;

while (j >= 0 &amp;&amp; arr[j] > key) {

arr[j + 1] = arr[j];
j = j - 1;

arr[j + 1] = key;

int main() {

int values[] = {10, 20, 30, 40, 50, 60, 70, 75, 80};

int numValues = sizeof(values) / sizeof(values[0]);

std::vector<int> sortedValues(values, values + numValues);

insertionSort(sortedValues);

TreeNode* balancedRoot = createBalancedBST(sortedValues, 0, numValues - 1);

int height = getHeightRecursive(balancedRoot);

std::cout << "Height of the balanced tree: " << height << std::endl;

return 0;

ANS-3

#include <iostream>
class TreeNode {

public:

int data;

TreeNode* left;

TreeNode* right;

int height;

TreeNode(int value) : data(value), left(NULL), right(NULL), height(1) {}

};

int getHeight(TreeNode* node) {

if (node == NULL) return 0;

return node->height;

void updateHeight(TreeNode* node) {

node->height = 1 + std::max(getHeight(node->left), getHeight(node->right));

int getBalanceFactor(TreeNode* node) {

if (node == NULL) return 0;

return getHeight(node->left) - getHeight(node->right);

TreeNode* rightRotate(TreeNode* y) {

TreeNode* x = y->left;

TreeNode* T2 = x->right;

x->right = y;

y->left = T2;
updateHeight(y);

updateHeight(x);

return x;

TreeNode* leftRotate(TreeNode* x) {

TreeNode* y = x->right;

TreeNode* T2 = y->left;

y->left = x;

x->right = T2;

updateHeight(x);

updateHeight(y);

return y;

TreeNode* balanceNode(TreeNode* node) {

int balance = getBalanceFactor(node);

if (balance > 1) {

if (getBalanceFactor(node->left) < 0) {

node->left = leftRotate(node->left);

return rightRotate(node);

if (balance < -1) {


if (getBalanceFactor(node->right) > 0) {

node->right = rightRotate(node->right);

return leftRotate(node);

return node;

TreeNode* insert(TreeNode* root, int value) {

if (root == NULL) {

return new TreeNode(value);

if (value < root->data) {

root->left = insert(root->left, value);

} else if (value > root->data) {

root->right = insert(root->right, value);

} else {

return root;

updateHeight(root);

return balanceNode(root);

void inorderTraversal(TreeNode* root) {

if (root == NULL) return;

inorderTraversal(root->left);
std::cout << root->data << " ";

inorderTraversal(root->right);

TreeNode* findMinNode(TreeNode* node) {

while (node->left != NULL) {

node = node->left;

return node;

TreeNode* deleteNode(TreeNode* root, int value) {

if (root == NULL) return root;

if (value < root->data) {

root->left = deleteNode(root->left, value);

} else if (value > root->data) {

root->right = deleteNode(root->right, value);

} else {

if (root->left == NULL || root->right == NULL) {

TreeNode* temp = (root->left) ? root->left : root->right;

if (temp == NULL) {

temp = root;

root = NULL;

} else {

*root = *temp;

delete temp;

} else {

TreeNode* temp = findMinNode(root->right);


root->data = temp->data;

root->right = deleteNode(root->right, temp->data);

if (root == NULL) {

return root;

updateHeight(root);

return balanceNode(root);

int main() {

TreeNode* root = NULL;

int insertValues[] = {10, 20, 30, 40, 50, 45, 35, 25, 15, 5, 8, 18, 28, 38, 48};

for (int i = 0; i < sizeof(insertValues) / sizeof(insertValues[0]); i++) {

root = insert(root, insertValues[i]);

std::cout << "In-order traversal of the constructed AVL tree: ";

inorderTraversal(root);

std::cout << std::endl;

int deleteValues[] = {38, 50, 10};

for (int i = 0; i < sizeof(deleteValues) / sizeof(deleteValues[0]); i++) {

root = deleteNode(root, deleteValues[i]);


}

std::cout << "In-order traversal of the updated AVL tree: ";

inorderTraversal(root);

std::cout << std::endl;

return 0;

ANS-4

#include <iostream>

#include <cstdlib>

class TreeNode {

public:

int data;

TreeNode* left;

TreeNode* right;

TreeNode(int value) : data(value), left(NULL), right(NULL) {}

};

int getHeight(TreeNode* node) {

if (node == NULL) return 0;

return 1 + std::max(getHeight(node->left), getHeight(node->right));

}
bool isAVLTree(TreeNode* root) {

if (root == NULL) return true;

int leftHeight = getHeight(root->left);

int rightHeight = getHeight(root->right);

if (std::abs(leftHeight - rightHeight) <= 1 &amp;&amp; isAVLTree(root->left) &amp;&amp;


isAVLTree(root->right)) {

return true;

return false;

int main() {

TreeNode* root = new TreeNode(10);

root->left = new TreeNode(5);

root->right = new TreeNode(15);

root->left->left = new TreeNode(3);

root->left->right = new TreeNode(7);

if (isAVLTree(root)) {

std::cout << "The given BST is also an AVL Tree." << std::endl;

} else {

std::cout << "The given BST is not an AVL Tree." << std::endl;

return 0;

}
ANS-5

#include <iostream>

#include <vector>

#include <algorithm>

class TreeNode {

public:

int data;

TreeNode* left;

TreeNode* right;

TreeNode(int value) : data(value), left(NULL), right(NULL) {}

};

class KaryTreeNode {

public:

int data;

std::vector<KaryTreeNode*> children;

KaryTreeNode(int value) : data(value) {}

};

TreeNode* insertBinaryTree(TreeNode* root, int value) {

if (root == NULL) {
return new TreeNode(value);

if (value < root->data) {

root->left = insertBinaryTree(root->left, value);

} else if (value > root->data) {

root->right = insertBinaryTree(root->right, value);

return root;

KaryTreeNode* insertKaryTree(KaryTreeNode* root, int value, int k) {

if (root == NULL) {

return new KaryTreeNode(value);

if (root->children.size() < k) {

root->children.push_back(insertKaryTree(root->children.back(), value, k));

} else {

KaryTreeNode* newNode = new KaryTreeNode(value);

root->children.push_back(newNode);

return root;

TreeNode* createBalancedBST(std::vector<int>&amp; sortedArray, int start, int end) {

if (start > end) {

return NULL;
}

int mid = (start + end) / 2;

TreeNode* root = new TreeNode(sortedArray[mid]);

root->left = createBalancedBST(sortedArray, start, mid - 1);

root->right = createBalancedBST(sortedArray, mid + 1, end);

return root;

TreeNode* findMinNode(TreeNode* node) {

while (node->left != NULL) {

node = node->left;

return node;

void preorderTraversal(TreeNode* root) {

if (root == NULL) return;

std::cout << root->data << " ";

preorderTraversal(root->left);

preorderTraversal(root->right);

void deleteNode(TreeNode*&amp; root, int value) {

if (root == NULL) return;

if (value < root->data) {

deleteNode(root->left, value);
} else if (value > root->data) {

deleteNode(root->right, value);

} else {

if (root->left == NULL) {

TreeNode* temp = root;

root = root->right;

delete temp;

} else if (root->right == NULL) {

TreeNode* temp = root;

root = root->left;

delete temp;

} else {

TreeNode* temp = findMinNode(root->right);

root->data = temp->data;

deleteNode(root->right, temp->data);

int main() {

TreeNode* binaryRoot = NULL;

KaryTreeNode* karyRoot = NULL;

std::vector<int> sortedValues;

int values[] = {10, 20, 30, 40, 50, 45, 35, 25, 15, 5, 8, 18, 28, 38, 48};

int numValues = sizeof(values) / sizeof(values[0]);

int k = 3;

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

binaryRoot = insertBinaryTree(binaryRoot, values[i]);


karyRoot = insertKaryTree(karyRoot, values[i], k);

sortedValues.push_back(values[i]);

std::sort(sortedValues.begin(), sortedValues.end());

TreeNode* balancedRoot = createBalancedBST(sortedValues, 0, numValues - 1);

std::cout << "Pre-order traversal of Binary Tree: ";

preorderTraversal(binaryRoot);

std::cout << std::endl;

deleteNode(balancedRoot, 18);

deleteNode(balancedRoot, 50);

deleteNode(balancedRoot, 25);

deleteNode(balancedRoot, 30);

deleteNode(balancedRoot, 28);

std::cout << "Pre-order traversal of the updated Balanced BST: ";

preorderTraversal(balancedRoot);

std::cout << std::endl;

return 0;

—----------------------------------------------------------------------------------------------------------------------------

WEEK-14 A

ANS-1

#include<iostream>

using namespace std;


class BTreeNode

int *keys;

int t;

BTreeNode **C;

int n;

bool leaf;

public:

BTreeNode(int _t, bool _leaf);

void insertNonFull(int k);

void splitChild(int i, BTreeNode *y);

void traverse();

BTreeNode *search(int k);

friend class BTree;

};

class BTree

BTreeNode *root;

int t;

public:

BTree(int _t)

{ root = NULL; t = _t; }

void traverse()
{ if (root != NULL) root->traverse(); }

BTreeNode* search(int k)

{ return (root == NULL)? NULL : root->search(k); }

void insert(int k);

};

BTreeNode::BTreeNode(int t1, bool leaf1)

t = t1;

leaf = leaf1;

keys = new int[2*t-1];

C = new BTreeNode *[2*t];

n = 0;

void BTreeNode::traverse()

int i;

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

if (leaf == false)

C[i]->traverse();

cout << " " << keys[i];

}
if (leaf == false)

C[i]->traverse();

BTreeNode *BTreeNode::search(int k)

int i = 0;

while (i < n &amp;&amp; k > keys[i])

i++;

if (keys[i] == k)

return this;

if (leaf == true)

return NULL;

return C[i]->search(k);

void BTree::insert(int k)

if (root == NULL)

root = new BTreeNode(t, true);

root->keys[0] = k;

root->n = 1;

else

{
if (root->n == 2*t-1)

BTreeNode *s = new BTreeNode(t, false);

s->C[0] = root;

s->splitChild(0, root);

int i = 0;

if (s->keys[0] < k)

i++;

s->C[i]->insertNonFull(k);

root = s;

else

root->insertNonFull(k);

void BTreeNode::insertNonFull(int k)

int i = n-1;

if (leaf == true)

while (i >= 0 &amp;&amp; keys[i] > k)


{

keys[i+1] = keys[i];

i--;

keys[i+1] = k;

n = n+1;

else

while (i >= 0 &amp;&amp; keys[i] > k)

i--;

if (C[i+1]->n == 2*t-1)

splitChild(i+1, C[i+1]);

if (keys[i+1] < k)

i++;

C[i+1]->insertNonFull(k);

void BTreeNode::splitChild(int i, BTreeNode *y)

{
BTreeNode *z = new BTreeNode(y->t, y->leaf);

z->n = t - 1;

for (int j = 0; j < t-1; j++)

z->keys[j] = y->keys[j+t];

if (y->leaf == false)

for (int j = 0; j < t; j++)

z->C[j] = y->C[j+t];

y->n = t - 1;

for (int j = n; j >= i+1; j--)

C[j+1] = C[j];

C[i+1] = z;

for (int j = n-1; j >= i; j--)

keys[j+1] = keys[j];

keys[i] = y->keys[t-1];

n = n + 1;

int main()

BTree t(3);
t.insert(10);

t.insert(20);

t.insert(5);

t.insert(6);

t.insert(12);

t.insert(30);

t.insert(7);

t.insert(17);

cout << "Traversal of the constructed tree is ";

t.traverse();

int k = 6;

(t.search(k) != NULL)? cout << "\nPresent" : cout << "\nNot Present";

k = 15;

(t.search(k) != NULL)? cout << "\nPresent" : cout << "\nNot Present";

return 0;

}
ANS-2

#include <iostream>

struct TreeNode {

int data;

TreeNode* left;

TreeNode* right;

bool isThreaded;

TreeNode(int value) : data(value), left(NULL), right(NULL), isThreaded(false) {}

};

class ThreadedBinaryTree {

public:

TreeNode* root;

ThreadedBinaryTree() : root(NULL) {}

void createThreadedTree(TreeNode* node, TreeNode*&amp; prev);

void inOrderTraversal(TreeNode* node);

void printThreadedTree();

};

void ThreadedBinaryTree::createThreadedTree(TreeNode* node, TreeNode*&amp; prev) {

if (node == NULL) {

return;

// Recursively convert the left subtree


createThreadedTree(node->left, prev);

if (node->left == NULL) {

node->left = prev;

node->isThreaded = true;

if (prev != NULL &amp;&amp; prev->isThreaded) {

prev->right = node;

prev->isThreaded = false;

prev = node;

// Recursively convert the right subtree

createThreadedTree(node->right, prev);

void ThreadedBinaryTree::inOrderTraversal(TreeNode* node) {

if (node == NULL) {

return;

TreeNode* current = node;

// Find the leftmost node

while (current->left != NULL &amp;&amp; !current->isThreaded) {

current = current->left;

while (current != NULL) {


// Print the node

std::cout << current->data << " ";

if (current->isThreaded) {

current = current->right;

} else {

current = current->right;

while (current != NULL &amp;&amp; !current->isThreaded) {

current = current->left;

void ThreadedBinaryTree::printThreadedTree() {

inOrderTraversal(root);

std::cout << std::endl;

int main() {

ThreadedBinaryTree tree;

// Construct a sample binary tree

tree.root = new TreeNode(1);

tree.root->left = new TreeNode(2);

tree.root->right = new TreeNode(3);

tree.root->left->left = new TreeNode(4);

tree.root->left->right = new TreeNode(5);

tree.root->right->left = new TreeNode(6);

tree.root->right->right = new TreeNode(7);


TreeNode* prev = NULL;

// Convert the binary tree to a threaded binary tree

tree.createThreadedTree(tree.root, prev);

// Print the nodes of the threaded binary tree in-order

std::cout << "Nodes of Threaded Binary Tree (in-order): ";

tree.printThreadedTree();

return 0;

ANS-3

#include <iostream>

#include <vector>

using namespace std;

const int ORDER = 3; // Example B+ Tree order, adjust as needed

struct BPlusTreeNode {

vector<int> keys;

vector<BPlusTreeNode*> children;
bool isLeaf;

BPlusTreeNode() : isLeaf(true) {}

};

class BPlusTree {

private:

BPlusTreeNode* root;

public:

BPlusTree() : root(nullptr) {}

void insert(int key) {

if (root == nullptr) {

root = new BPlusTreeNode();

root->keys.push_back(key);

} else {

insertKey(root, key);

void insertKey(BPlusTreeNode* node, int key) {

if (node->isLeaf) {

insertIntoLeaf(node, key);

} else {

int i = 0;

while (i < node->keys.size() &amp;&amp; key > node->keys[i]) {

i++;

insertKey(node->children[i], key);
}

void insertIntoLeaf(BPlusTreeNode* leaf, int key) {

leaf->keys.push_back(key);

sort(leaf->keys.begin(), leaf->keys.end());

if (leaf->keys.size() >= ORDER) {

splitLeaf(leaf);

void splitLeaf(BPlusTreeNode* leaf) {

BPlusTreeNode* newLeaf = new BPlusTreeNode();

int mid = leaf->keys.size() / 2;

newLeaf->keys.assign(leaf->keys.begin() + mid, leaf->keys.end());

leaf->keys.erase(leaf->keys.begin() + mid, leaf->keys.end());

if (leaf->isLeaf) {

newLeaf->isLeaf = true;

leaf->isLeaf = true;

if (leaf->parent == nullptr) {

// Create a new root

BPlusTreeNode* newRoot = new BPlusTreeNode();

newRoot->keys.push_back(newLeaf->keys[0]);

newRoot->children.push_back(leaf);

newRoot->children.push_back(newLeaf);

leaf->parent = newRoot;

newLeaf->parent = newRoot;

root = newRoot;
} else {

int index = insertKeyIntoParent(leaf->parent, newLeaf->keys[0]);

newLeaf->parent = leaf->parent;

leaf->parent->children.insert(leaf->parent->children.begin() + index + 1, newLeaf);

int insertKeyIntoParent(BPlusTreeNode* parent, int key) {

int index = 0;

while (index < parent->keys.size() &amp;&amp; key > parent->keys[index]) {

index++;

parent->keys.insert(parent->keys.begin() + index, key);

return index;

void printTree() {

if (root != nullptr) {

printNode(root);

void printNode(BPlusTreeNode* node) {

for (int i = 0; i < node->keys.size(); i++) {

cout << node->keys[i] << " ";

if (!node->isLeaf) {

for (int i = 0; i < node->children.size(); i++) {

printNode(node->children[i]);

}
}

};

int main() {

BPlusTree bPlusTree;

vector<int> keys = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};

for (int key : keys) {

bPlusTree.insert(key);

bPlusTree.printTree();

return 0;

ANS-4

#include <bits/stdc++.h>

#include <vector>

using namespace std;

const int ORDER = 3;

struct BPlusTreeNode {

vector<int> keys;

vector<BPlusTreeNode*> children;

bool isLeaf;

BPlusTreeNode() : isLeaf(true) {}
};

class BPlusTree {

private:

BPlusTreeNode* root;

public:

BPlusTree() : root(nullptr) {}

void insert(int key) {

if (root == nullptr) {

root = new BPlusTreeNode();

root->keys.push_back(key);

} else {

insertKey(root, key);

void insertKey(BPlusTreeNode* node, int key) {

if (node->isLeaf) {

node->keys.push_back(key);

sort(node->keys.begin(), node->keys.end());

if (node->keys.size() >= ORDER) {

splitLeaf(node);

} else {

// Handle insertion into internal nodes if needed

// ... (rest of the code for searching and printing as shown in previous examples)
};

int main() {

BPlusTree bPlusTree;

vector<int> keys = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};

for (int key : keys) {

bPlusTree.insert(key);

int searchKey = 45;

if (bPlusTree.search(searchKey)) {

cout << "Key " << searchKey << " found in the B+ Tree." << endl;

} else {

cout << "Key " << searchKey << " not found in the B+ Tree." << endl;

return 0;

—----------------------------------------------------------------------------------------------------------------------------

WEEK-15 B & 16 A

ANS-1

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;


const int V = 8; // Number of nodes in the graph

bool isSafe(int v, vector<vector<int>>& graph, vector<int>& path, int pos) {

if (graph[path[pos - 1]][v] == 0)

return false;

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

if (path[i] == v)

return false;

return true;

bool hamiltonianUtil(vector<vector<int>>& graph, vector<int>& path, int pos) {

if (pos == V) {

if (graph[path[pos - 1]][path[0]] == 1)

return true;

else

return false;

for (int v = 1; v < V; ++v) {

if (isSafe(v, graph, path, pos)) {

path[pos] = v;

if (hamiltonianUtil(graph, path, pos + 1) == true)

return true;

path[pos] = -1;

return false;
}

void hamiltonianPath(vector<vector<int>>& graph) {

vector<int> path(V, -1);

path[0] = 0;

if (hamiltonianUtil(graph, path, 1) == false) {

cout << "No Hamiltonian path exists." << endl;

return;

cout << "Hamiltonian Path: ";

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

cout << char('A' + path[i]) << " ";

cout << char('A') << endl;

int main() {

vector<vector<int>> graph = {

{0, 15, 5, 20, 8, 15, 4, 21},

{15, 0, 10, 12, 0, 7, 0, 6},

{5, 10, 0, 0, 17, 5, 8, 0},

{20, 12, 0, 0, 12, 1, 9, 3},

{8, 0, 17, 12, 0, 3, 6, 7},

{15, 7, 5, 1, 3, 0, 5, 14},

{4, 0, 8, 9, 6, 5, 0, 8},

{21, 6, 0, 3, 7, 14, 8, 0}

};

hamiltonianPath(graph);
return 0;

#include <iostream>

#include <vector>

#include <queue>

#include <climits>

using namespace std;

void dijkstra(vector<vector<int>>& graph, int src) {

int V = graph.size();

vector<int> dist(V, INT_MAX);

dist[src] = 0;

priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

pq.push({0, src});

while (!pq.empty()) {

int u = pq.top().second;

pq.pop();

for (int v = 0; v < V; ++v) {

if (graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {


dist[v] = dist[u] + graph[u][v];

pq.push({dist[v], v});

cout << "Shortest distances from F to other nodes:\n";

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

if (i != src) {

cout << "F to " << char('A' + i) << ": " << dist[i] << endl;

int main() {

vector<vector<int>> graph = {

{0, 15, 5, 20, 8, 15, 4, 21},

{15, 0, 10, 12, 0, 7, 0, 6},

{5, 10, 0, 0, 17, 5, 8, 0},

{20, 12, 0, 0, 12, 1, 9, 3},

{8, 0, 17, 12, 0, 3, 6, 7},

{15, 7, 5, 1, 3, 0, 5, 14},

{4, 0, 8, 9, 6, 5, 0, 8},

{21, 6, 0, 3, 7, 14, 8, 0}

};

dijkstra(graph, 5); // 'F' is node 5 in the graph

return 0;

}
ANS-2

#include<bits/stdc++.h>

using namespace std;

class Edge {

public:

int src, dest, weight;

};

class Graph {

public:

int V, E;

Edge* edge;

};

Graph* createGraph(int V, int E) {

Graph* graph = new Graph;

graph->V = V;

graph->E = E;
graph->edge = new Edge[E];

return graph;

class subset {

public:

int parent;

int rank;

};

int find(subset subsets[], int i) {

if (subsets[i].parent != i)

subsets[i].parent = find(subsets, subsets[i].parent);

return subsets[i].parent;

void Union(subset subsets[], int x, int y) {

int xroot = find(subsets, x);

int yroot = find(subsets, y);

if (subsets[xroot].rank < subsets[yroot].rank)

subsets[xroot].parent = yroot;

else if (subsets[xroot].rank > subsets[yroot].rank)

subsets[yroot].parent = xroot;

else {

subsets[yroot].parent = xroot;

subsets[xroot].rank++;

int myComp(const void* a, const void* b) {

Edge* a1 = (Edge*)a;
Edge* b1 = (Edge*)b;

return a1->weight > b1->weight;

void KruskalMST(Graph* graph) {

int V = graph->V;

Edge result[V];

int e = 0;

int i = 0;

qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);

subset *subsets = new subset[( V * sizeof(subset) )];

for (int v = 0; v < V; ++v) {

subsets[v].parent = v;

subsets[v].rank = 0;

while (e < V - 1 && i < graph->E) {

Edge next_edge = graph->edge[i++];

int x = find(subsets, next_edge.src);

int y = find(subsets, next_edge.dest);

if (x != y) {

result[e++] = next_edge;

Union(subsets, x, y);

cout <<"Following are the edges in the constructed MST\n";

for (i = 0; i < e; ++i)

cout <<result[i].src<<" -- "<<result[i].dest<<" == "<<result[i].weight<<endl;

return;

int main() {
int V = 4;

int E = 5;

Graph* graph = createGraph(V, E);

graph->edge[0].src = 0;

graph->edge[0].dest = 1;

graph->edge[0].weight = 10;

graph->edge[1].src = 0;

graph->edge[1].dest = 2;

graph->edge[1].weight = 6;

graph->edge[2].src = 0;

graph->edge[2].dest = 3;

graph->edge[2].weight = 5;

graph->edge[3].src = 1;

graph->edge[3].dest = 3;

graph->edge[3].weight = 15;

graph->edge[4].src = 2;

graph->edge[4].dest = 3;

graph->edge[4].weight = 4;

KruskalMST(graph);

return 0;

#include<bits/stdc++.h>
using namespace std;

const int MAX = 1e4 + 5;

bool marked[MAX];

vector <pair<long long, int> > adj[MAX];

long long prim(int x) {

priority_queue<pair<long long, int>, vector<pair<long long, int> >, greater<pair<long long, int> > >
Q;

int y;

long long minimumCost = 0;

pair<long long, int> p;

Q.push(make_pair(0, x));

while(!Q.empty()) {

p = Q.top();

Q.pop();

x = p.second;

if(marked[x] == true)

continue;

minimumCost += p.first;

marked[x] = true;

for(int i = 0;i < adj[x].size();++i) {

y = adj[x][i].second;

if(marked[y] == false)

Q.push(adj[x][i]);

return minimumCost;

int main() {

int nodes = 3, edges = 3;


int x, y;

long long weight, minimumCost;

int graph[3][3] = { {1, 2, 10}, {2, 3, 15}, {3, 1, 20} };

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

x = graph[i][0];

y = graph[i][1];

weight = graph[i][2];

adj[x].push_back(make_pair(weight, y));

adj[y].push_back(make_pair(weight, x));

minimumCost = prim(1);

cout << minimumCost << endl;

return 0;

ANS-3

#include<bits/stdc++.h>

using namespace std;

class Graph {

public:

map<int, bool> visited;


map<int, list<int>> adj;

void addEdge(int v, int w);

void DFS(int v);

};

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

void Graph::DFS(int v) {

visited[v] = true;

cout << v << " ";

list<int>::iterator i;

for(i = adj[v].begin(); i != adj[v].end(); ++i)

if (!visited[*i])

DFS(*i);

int main() {

Graph g;

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

cout << "Depth First Traversal (starting from vertex 2): ";

g.DFS(2);

return 0;

}
#include<iostream>

#include <list>

using namespace std;

class Graph {

public:

int V;

list<int> *adj;

Graph(int V);

void addEdge(int v, int w);

void BFS(int s);

};

Graph::Graph(int V) {

this->V = V;

adj = new list<int>[V];

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

void Graph::BFS(int s) {

bool *visited = new bool[V];

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

visited[i] = false;

list<int> queue;
visited[s] = true;

queue.push_back(s);

list<int>::iterator i;

while(!queue.empty()) {

s = queue.front();

cout << s << " ";

queue.pop_front();

for (i = adj[s].begin(); i != adj[s].end(); ++i) {

if (!visited[*i]) {

queue.push_back(*i);

visited[*i] = true;

int main() {

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

cout << "Breadth First Traversal (starting from vertex 2): ";

g.BFS(2);

return 0;

}
ANS-4

#include <iostream>

#include <vector>

#include <climits>

using namespace std;

const int V = 5;

int minKey(int key[], bool mstSet[]) {

int min = INT_MAX, min_index;

for (int v = 0; v < V; ++v)

if (mstSet[v] == false && key[v] < min)

min = key[v], min_index = v;

return min_index;

void printMST(int parent[], vector<vector<int>>& graph) {

cout << "Edge \tWeight\n";

for (int i = 1; i < V; ++i)

cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << "\n";

void primMST(vector<vector<int>>& graph) {

int parent[V];

int key[V];

bool mstSet[V];
for (int i = 0; i < V; ++i) {

key[i] = INT_MAX, mstSet[i] = false;

key[0] = 0;

parent[0] = -1;

for (int count = 0; count < V - 1; ++count) {

int u = minKey(key, mstSet);

mstSet[u] = true;

for (int v = 0; v < V; ++v) {

if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) {

parent[v] = u, key[v] = graph[u][v];

printMST(parent, graph);

int main() {

vector<vector<int>> graph = {

{0, 3, 6, 2, 0},

{3, 0, 0, 4, 2},

{6, 0, 0, 4, 4},

{2, 4, 4, 0, 0},

{0, 2, 4, 0, 0}

};
primMST(graph);

return 0;

ANS-5

#include <iostream>

#include <list>

#include <queue>

#include <stack>

#include <unordered_map>

using namespace std;

class Graph {

unordered_map<char, list<pair<char, int>>> adjList;

public:

void addEdge(char u, char v, int distance) {

adjList[u].push_back({v, distance});

adjList[v].push_back({u, distance}); // If the graph is undirected

}
void BFS(char source, char destination) {

unordered_map<char, bool> visited;

unordered_map<char, char> parent;

queue<char> q;

q.push(source);

visited[source] = true;

parent[source] = source;

while (!q.empty()) {

char current = q.front();

q.pop();

if (current == destination) {

cout << "Path found from " << source << " to " << destination << ": ";

while (current != source) {

cout << current << " <- ";

current = parent[current];

cout << source << endl;

return;

for (auto neighbor : adjList[current]) {

char nextNode = neighbor.first;

if (!visited[nextNode]) {

q.push(nextNode);

visited[nextNode] = true;

parent[nextNode] = current;

}
}

cout << "Path not found from " << source << " to " << destination << endl;

void DFSUtil(char current, unordered_map<char, bool>& visited) {

visited[current] = true;

cout << current << " ";

for (auto neighbor : adjList[current]) {

char nextNode = neighbor.first;

if (!visited[nextNode]) {

DFSUtil(nextNode, visited);

void DFS(char source) {

unordered_map<char, bool> visited;

cout << "DFS traversal starting from node " << source << ": ";

DFSUtil(source, visited);

cout << endl;

};

int main(){

Graph g;

g.addEdge('S','A',3);

g.addEdge('A','D',9);

g.addEdge('A','E',8);
g.addEdge('S','B',6);

g.addEdge('B','F',12);

g.addEdge('B','G',14);

g.addEdge('S','C',5);

g.addEdge('C','H',7);

g.addEdge('H','I',5);

g.addEdge('H','J',6);

g.addEdge('I','K',1);

g.addEdge('I','L',10);

g.addEdge('I','M',2);

char source='S';

char destination='I';

g.BFS(source, destination);

g.DFS(source);

return 0;

ANS-6

#include<iostream>

#include <list>

using namespace std;


class Graph {

public:

int V;

list<int> *adj;

Graph(int V);

void addEdge(int v, int w);

void BFS(int s);

};

Graph::Graph(int V) {

this->V = V;

adj = new list<int>[V];

void Graph::addEdge(int v, int w) {

adj[v].push_back(w); // Add w to v’s list for a digraph.

void Graph::BFS(int s) {

bool *visited = new bool[V];

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

visited[i] = false;

list<int> queue;

visited[s] = true;

queue.push_back(s);

list<int>::iterator i;

while(!queue.empty()) {

s = queue.front();

cout << s << " ";

queue.pop_front();

for(i = adj[s].begin(); i != adj[s].end(); ++i) {


if (!visited[*i]) {

queue.push_back(*i);

visited[*i] = true;

int main() {

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

cout << "Following is Breadth First Traversal (starting from vertex 2): ";

g.BFS(2);

return 0;

You might also like