0% found this document useful (0 votes)
5 views

adsa file

The document provides a collection of programming tasks and their solutions, primarily focused on data structures and algorithms. It includes functions for array manipulation, linked list operations, binary tree traversals, and graph algorithms. Each section contains code snippets in C++ along with explanations for the respective tasks.

Uploaded by

Silent
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)
5 views

adsa file

The document provides a collection of programming tasks and their solutions, primarily focused on data structures and algorithms. It includes functions for array manipulation, linked list operations, binary tree traversals, and graph algorithms. Each section contains code snippets in C++ along with explanations for the respective tasks.

Uploaded by

Silent
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/ 25

1

Ashutosh
2

Index
S.No Topic Page no.

1 Find the Maximum and Minimum Elements in an 3


Array: Write a function to find the maximum and
minimum elements in an array.
2 Reverse an Array: Write a function to reverse an 4
array in place.

3 Find the Kth Smallest/Largest Element in an 5


Array: Write a function to find the Kth
smallest or largest element in an array.

4 Write a program to sort all 0s,1s and 2s 6

5 Write a function to move all zeroes in an array 7


to the end while maintaining the relative order
of other elements
6 Write a function to reverse a singly linked list 8

7 Write a function to find the middle element of a 9


linked list.
8 Write a function to detect if a cycle exists in a 11
linked list.
9 Write a function to check if a string containing 12
parentheses is balanced.
10 Find the next greater element using a stack 13

11 Write a function to generate binary numbers 14


from1 to N using a queue.
12 Write a function to perform inorder traversal of a 15
binary tree

13 Write a function to perform preorder traversal of 16


a binary tree.

14 Write a function to perform postorder traversal 16


of a binary tree

15 Write a function to perform level order traversal 17


of a binary tree.

16 Write a function to find the height of a binary 18


tree.

17 Write a function to find the diameter of a binary 19


tree.
3

18 Write a function to find the lowest common 20


ancestor of two nodes in a binary tree.

19 Write a function to perform BFS on a graph from 22


a given start vertex.

20 Write a function to perform DFS on a graph from 23


a given start vertex.

Q1 Find the Maximum and Minimum Elements in an Array: Write a function to


find the maximum and minimum elements in an array.
Code : #include<iostream>
#include<vector>
#include<climits>

using namespace std;

int CalculateMax(vector<int>& arr){


int maximum = INT_MIN;
for(int i=0; i<arr.size();i++){
if(arr[i]>maximum) maximum = arr[i];
}
return maximum;
}

int CalculateMin(vector<int>& arr){


int minimum = INT_MAX;
for(int i=0; i<arr.size();i++){
if(arr[i]<minimum) minimum = arr[i];
}
return minimum;
}

int main(){
int n;
cout<<"Enter the size of the array : ";
cin>>n;

vector<int> arr(n);
for(int i=0;i<n;i++) cin>>arr[i];

int maximum_elem = CalculateMax(arr);


int minimum_elem = CalculateMin(arr);

cout<<"Min element : "<<minimum_elem<<endl;


cout<<"Max element : "<<maximum_elem<<endl;
4

Outpu
t:

Q2 Reverse an Array: Write a function to reverse an array in place.

Code: #include<iostream>
#include<vector>
#include<climits>

using namespace std;

void reverseArray(vector<int>& arr){


int start = 0;
int end = arr.size()-1;
while(start<end){
swap(arr[start++], arr[end--]);
}
}

void displayArray(vector<int>& arr){


cout<<"Array : ";
for(auto i : arr) cout<<i<<" ";
cout<<endl;
}

int main(){
int n;
cout<<"Enter the size of the array : ";
cin>>n;

vector<int> arr(n);
for(int i=0;i<n;i++) cin>>arr[i];

reverseArray(arr);
displayArray(arr);

}
5

Outpu
t:

Q3 Find the Kth Smallest/Largest Element in an Array: Write a function to find


the Kth
smallest or largest element in an array.

Code: #include <iostream>


#include <vector>
#include <algorithm>

using namespace std;

int quickselect(vector<int>& arr, int left, int right, int k) {


int pivot = arr[left];
int pivot_idx = left;
int i = left+1, j = right;
while(i <= j){
if(arr[i]>pivot && arr[j]<pivot){
swap(arr[i],arr[j]);
i++;
j--;
}
if(arr[j]>=pivot) j--;
if(arr[i]<=pivot) i++;
}
swap(arr[pivot_idx],arr[j]);
if(j == k) return arr[j];
else if(j < k) return quickselect(arr,j+1,right,k);
else return quickselect(arr,left,j-1,k);
}

pair<int, int> KthSmallestAndLargest(vector<int>& arr, int k) {


int n = arr.size();
int ksmallest = quickselect(arr, 0, n - 1, k - 1);
int klargest = quickselect(arr, 0, n - 1, n - k);
return {ksmallest, klargest};
}
6

int main() {
int n, k;
cout << "Enter the size of the array: ";
cin >> n;
vector<int> arr(n);
cout << "Enter the array elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
cout << "Enter the value of k: ";
cin >> k;
pair<int, int> p = KthSmallestAndLargest(arr, k);

cout << k << " smallest element is: " << p.first << endl;
cout << k << " largest element is: " << p.second << endl;

return 0;
}

Outpu
t:

Q4 Write a program to sort all 0s,1s and 2s

Code: #include<iostream>
#include<vector>
using namespace std;

void sorting(vector<int> & arr){


int low = 0, mid = 0, high = arr.size()-1;
while(mid<=high){
if(arr[mid]==0) swap(arr[low++],arr[mid++]);
else if(arr[mid]==1) mid
else swap(arr[mid],arr[high--]);
}
}

void display(vector<int>& arr){


cout<<"Sorted array :";
for(auto i : arr) cout<<i<<" ";
}

int main(){

int n, k;
cout << "Enter the size of the array: ";
cin >> n;

vector<int> arr(n);
cout << "Enter the array elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
7

sorting(arr);
display(arr);

return 0;
}

Outpu
t:

Q5 Write a function to move all zeroes in an array to the end while maintaining
the relative order of other elements
Code: #include<iostream>
#include<vector>
using namespace std;

void moveZerosToEnd(vector<int>& arr){


int low=0;
for(int i=0;i<arr.size();i++){
if(arr[i]!=0) swap(arr[i],arr[low++]);
}
}

void display(vector<int>& arr){


cout<<"Sorted array :";
for(auto i : arr) cout<<i<<" ";
}

int main(){
int n, k;
cout << "Enter the size of the array: ";
cin >> n;

vector<int> arr(n);
cout << "Enter the array elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];

moveZerosToEnd(arr);
display(arr);

return 0;
}
8

Outpu
t:

Q6 Write a function to reverse a singly linked list

Code: #include<iostream>
using namespace std;

class Node{
public:
int data;
Node* next;
Node(int value){
data = value;
next = NULL;
}
};

class Linkedlist{
Node* head;
Node* tail;
public:
Linkedlist(){
head=NULL;
}

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


Node *temp = new Node(arr[0]);
if(head==NULL){
head=tail=temp;
}
for(int i=1; i<n; i++){
temp = new Node(arr[i]);
tail->next = temp;
tail = temp;
}
}

void display(){
Node* temp = head;
if(head==NULL) cout<<"List is empty";
while(temp){
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
9

void reverseLL(){
Node* prev = NULL;
Node*temp = head;
while(temp){
Node* front = temp->next;
temp->next = prev;
prev = temp;
temp = front;
}
head = prev;
}

};

int main(){
int arr[10]={1,2,3,4,5,6,7,8,9,10};
int n = sizeof(arr)/sizeof(arr[0]);

Linkedlist list1;

list1.insertArrValues(arr,n);

cout<<"Linkedlist : ";
list1.display();

list1.reverseLL();
cout<<"Linkedlist after reversing : ";
list1.display();

return 0;
}

Outpu
t:

Q7 Write a function to find the middle element of a linked list.

Code: #include<iostream>
using namespace std;

class Node{
public:
int data;
Node* next;
Node(int value){
data = value;
next = NULL;
}
};

class Linkedlist{
10

Node* head;
Node* tail;
public:
Linkedlist(){
head=NULL;
}

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


Node *temp = new Node(arr[0]);
if(head==NULL){
head=tail=temp;
}
for(int i=1; i<n; i++){
temp = new Node(arr[i]);
tail->next = temp;
tail = temp;
}
}

void display(){
Node* temp = head;
if(head==NULL) cout<<"List is empty";
while(temp){
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}

int middleofLL(){
Node* slow = head;
Node* fast = head;
while(fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
return slow->data;
}

};

int main(){
int arr[10]={1,2,3,4,5,6,7,8,9,10};
int n = sizeof(arr)/sizeof(arr[0]);

Linkedlist list1;

list1.insertArrValues(arr,n);

cout<<"Linkedlist : ";
list1.display();
11

int mid = list1.middleofLL();


cout<<"Middle of the linked list : "<<mid<<endl;

return 0;
}

Outpu
t:

Q8 Write a function to detect if a cycle exists in a linked list.

Code: #include<iostream>
using namespace std;

class Node{
public:
int data;
Node* next;
Node(int value){
data = value;
next = NULL;
}
};

class Linkedlist{
Node* head;
Node* tail;
public:
Linkedlist(){
head=NULL;
}

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


Node *temp = new Node(arr[0]);
if(head==NULL){
head=tail=temp;
}
for(int i=1; i<n; i++){
temp = new Node(arr[i]);
tail->next = temp;
tail = temp;
}
}

bool detectCycle(){
Node* slow = head;
Node* fast = head;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
12

}
return false;
}

};

int main(){
int arr[10]={1,2,3,4,5,6,7,8,9,10};
int n = sizeof(arr)/sizeof(arr[0]);

Linkedlist list1;

list1.insertArrValues(arr,n);
cout<<"Linked list created"<<endl;

bool res = list1.detectCycle();


if(res) cout<<"Cycle exists in the given linked list"<<endl;
else cout<<"Cycle doesn't exist in the given linked list"<<endl;

return 0;
}

Outpu
t:

Q9 Write a function to check if a string containing parentheses is balanced.

Code: #include<iostream>
#include<vector>
#include<stack>

using namespace std;

bool validParantheses(vector<char> & s){


stack<char> st;
for(auto &ch : s){
if(ch == '{') st.push('}');
else if(ch == '(') st.push(')');
else if(ch == '[') st.push(']');
else if(st.empty() || st.top()!=ch) return false;
else st.pop();
}
return st.empty();
}

int main(){
int n;
cout<<"Enter the size of the string : ";
cin>>n;
vector<char> s(n);
for(int i=0; i<n; i++) cin>>s[i];
13

bool res = validParantheses(s);


if(res) cout<<"It is a valid parantheses "<<endl;
else cout<<"It is an invalid parantheses "<<endl;

return 0;
}

Outpu
t:

Q10 Find the next greater element using a stack

Code: #include<iostream>
#include<vector>
#include<stack>
using namespace std;

vector<int> nextLargerElement(vector<int> &arr) {


int n = arr.size();
vector<int> result(n, -1);
stack<int> st;
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && st.top() <= arr[i]) st.pop();
if (!st.empty()) result[i] = st.top();
st.push(arr[i]);
}
return result;
}

int main() {

vector<int> arr = {3,8,10,5,2,23,16,9,20};


vector<int> result = nextLargerElement(arr);

for (int x : result) cout << x << " ";

return 0;
}

Outpu
t:

Q11 Write a function to generate binary numbers from1 to N using a queue.

Code: #include <iostream>


#include <queue>
14

#include <vector>
using namespace std;

vector<string> generateBinaryNumbers(int N) {
vector<string> result;
queue<string> q;
q.push("1");

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


string current = q.front();
q.pop();

result.push_back(current);
s
q.push(current + "0");
q.push(current + "1");
}

return result;
}

int main() {
int n;
cout << "Enter the value of N: ";
cin >> n;

vector<string> binaryNumbers = generateBinaryNumbers(N);

for(auto &it : binaryNumbers) cout << it << " ";

cout << endl;

return 0;
}

Outpu
t:

Q12 Write a function to perform inorder traversal of a binary tree

Code: #include <iostream>


using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int value){
val = value;
15

left = NULL;
right = NULL;
}
};

void inorderTraversal(TreeNode* root) {


if (root == nullptr) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}

int main() {

TreeNode* root = new TreeNode(1);


root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);

cout << "Inorder traversal of the binary tree: ";


inorderTraversal(root);
cout << endl;

return 0;
}

Outpu
t:

Q13 Write a function to perform preorder traversal of a binary tree.

Code: #include <iostream>


using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int value) {
val = value;
left = nullptr;
right = nullptr;
}
};

void preorderTraversal(TreeNode* root) {


if (root == nullptr) return;
cout << root->val << " ";
16

preorderTraversal(root->left);
preorderTraversal(root->right);
}

int main() {

TreeNode* root = new TreeNode(1);


root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);

cout << "Preorder traversal of the binary tree: ";


preorderTraversal(root);
cout << endl;

return 0;
}

Outpu
t:

Q14 Write a function to perform postorder traversal of a binary tree

Code: #include <iostream>


using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int value) {
val = value;
left = nullptr;
right = nullptr;
}
};

void postorderTraversal(TreeNode* root) {


if (root == nullptr) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}

int main() {
17

TreeNode* root = new TreeNode(1);


root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);

cout << "Postorder traversal of the binary tree: ";


postorderTraversal(root);
cout << endl;

return 0;
}

Outpu
t:

Q15 Write a function to perform level order traversal of a binary tree.

Code: #include <iostream>


#include <queue>
using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int value) {
val = value;
left = nullptr;
right = nullptr;
}
};

void levelOrderTraversal(TreeNode* root) {


if (root == nullptr) return;

queue<TreeNode*> q;
q.push(root);

while (!q.empty()) {
TreeNode* current = q.front();
q.pop();
cout << current->val << " ";
if (current->left != nullptr) q.push(current->left);
if (current->right != nullptr) q.push(current->right);
}
}
18

int main() {

TreeNode* root = new TreeNode(1);


root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);

cout << "Level order traversal of the binary tree: ";


levelOrderTraversal(root);
cout << endl;

return 0;
}

Outpu
t:

Q16 Write a function to find the height of a binary tree.

Code: #include <iostream>


using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int value) {
val = value;
left = nullptr;
right = nullptr;
}
};

int findHeight(TreeNode* root) {


if (root == nullptr) return 0;
int leftHeight = findHeight(root->left);
int rightHeight = findHeight(root->right);
return 1 + max(leftHeight, rightHeight);
}

int main() {

TreeNode* root = new TreeNode(1);


root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
19

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


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

int height = findHeight(root);


cout << "Height of the binary tree: " << height << endl;

return 0;
}

Outpu
t:

Q17 Write a function to find the diameter of a binary tree.

Code: #include <iostream>


using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int value) {
val = value;
left = nullptr;
right = nullptr;
}
};

int findDiameter(TreeNode* root, int& diameter) {


if (root == nullptr) return 0;
int leftHeight = findDiameter(root->left, diameter);
int rightHeight = findDiameter(root->right, diameter);
diameter = max(diameter, leftHeight + rightHeight);
return 1 + max(leftHeight, rightHeight);
}

int calculateDiameter(TreeNode* root) {


int diameter = 0;
findDiameter(root, diameter);
return diameter;
}

int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
20

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

int diameter = calculateDiameter(root);


cout << "Diameter of the binary tree: " << diameter << endl;

return 0;
}

Outpu
t:
Q18 Write a function to find the lowest common ancestor of two nodes in a
binary tree.

Code: #include <iostream>


using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int value) {
val = value;
left = nullptr;
right = nullptr;
}
};

TreeNode* findLCA(TreeNode* root, TreeNode* p, TreeNode* q) {


if (root == nullptr || root == p || root == q) return root;

TreeNode* leftLCA = findLCA(root->left, p, q);


TreeNode* rightLCA = findLCA(root->right, p, q);

if (leftLCA != nullptr && rightLCA != nullptr) return root;

return (leftLCA != nullptr) ? leftLCA : rightLCA;


}

int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
root->left->right->right = new TreeNode(8);

TreeNode* p = root->left->right;
TreeNode* q = root->left->right->right;
21

TreeNode* lca = findLCA(root, p, q);

if (lca != nullptr) {
cout << "Lowest Common Ancestor of "<<p->val<<" and "<<q-
>val<<" is: "<<lca->val<<endl;
} else {
cout<<"Lowest Common Ancestor not found."<<endl;
}

return 0;
}

Outpu
t:
Q19 Write a function to perform BFS on a graph from a given start vertex.

Code: #include <iostream>


#include <queue>
#include <vector>
using namespace std;

void bfs(vector<vector<int>>& adj, int s){


queue<int> q;
vector<bool> visited(adj.size(), false);
visited[s] = true;
q.push(s);
while (!q.empty()) {
int curr = q.front();
q.pop();
cout << curr << " ";

for (int x : adj[curr]) {


if (!visited[x]) {
visited[x] = true;
q.push(x);
}
}
}
}

void addEdge(vector<vector<int>>& adj,int u, int v){


adj[u].push_back(v);
adj[v].push_back(u);
}

int main(){

int V = 5;
vector<vector<int>> adj(V);
22

addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 4);

cout << "BFS starting from 0 : ";


bfs(adj, 0);

return 0;
}

Outpu
t:

Q20 Write a function to perform DFS on a graph from a given start vertex.

Code: #include<iostream>
#include<vector>

using namespace std;

void DFSRec(vector<vector<int>> &adj, vector<bool> &visited, int s){


visited[s] = true;
cout << s << " ";
for (int i : adj[s])
if (visited[i] == false)
DFSRec(adj, visited, i);
}

void DFS(vector<vector<int>> &adj, int s){


vector<bool> visited(adj.size(), false);
DFSRec(adj, visited, s);
}

void addEdge(vector<vector<int>> &adj, int s, int t){


adj[s].push_back(t);
adj[t].push_back(s);
}

int main(){
int V = 5;
vector<vector<int>> adj(V);

vector<vector<int>> edges={{1, 2},{1, 0},{2, 0},{2, 3},{2, 4}};


for (auto &e : edges)
23

addEdge(adj, e[0], e[1]);

int start = 1;
cout << "DFS from source: " << start << endl;
DFS(adj, start);

return 0;
}

Outpu
t:
24
25

You might also like