Advanced Dsa File - PR - Edited
Advanced Dsa File - PR - Edited
Lab File
For
BACHELOR OF
UTTAR PRADESH
1|P a g e
PROBLEM NO. : 1
PROGRAM :
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Part 1: Missing Number in Array
2|P a g e
int arr[] = {1, 2, 4, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Missing number: " << findMissingNumber(arr, size) << endl;
// Part 3: Power of 2
int number = 16;
if (isPowerOfTwo(number))
cout << number << " is a power of 2." << endl;
else
cout << number << " is not a power of 2." << endl;
return 0;
}
OUTPUT :
3|P a g e
PROBLEM NO. : 2
AIM : WAP Set kth bit, Toggle bits given range, Find first set bit, Check whether
K-th bit is set, Rightmost different bit
PROGRAM :
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Part 1: Set K-th Bit
int n = 5, k = 1;
cout << "Number after setting " << k << "th bit: " << setKthBit(n, k) <<
endl;
4|P a g e
// Part 2: Toggle Bits Given Range
n = 50; // 110010
int l = 2, r = 5;
cout << "Number after toggling bits from " << l << " to " << r << " is " <<
toggleBitsInRange(n, l, r) << endl;
return 0;
}
OUTPUT :
5|P a g e
PROBLEM NO. :3
AIM : WAP Detecting Duplicates in Array, Finding Unique element in Array, Finding Maximum
XOR Subarray, Longest Consecutive 1's (Hamming Weight)
PROGRAM :
#include <iostream>
#include <unordered_set>
#include <vector>
#include <algorithm>
using namespace std;
6|P a g e
// Function to find the longest consecutive 1's (Hamming weight)
int longestConsecutiveOnes(int n) {
int max_count = 0, count = 0;
while (n) {
if (n & 1) {
count++;
max_count = max(max_count, count);
} else {
count = 0;
}
n >>= 1;
}
return max_count;
}
int main() {
// Part 1: Detecting Duplicates in Array
int arr1[] = {1, 2, 3, 4, 5, 3};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
if (hasDuplicates(arr1, size1))
cout << "Array has duplicates." << endl;
else
cout << "Array has no duplicates." << endl;
OUTPUT :
7|P a g e
PROBLEM NO. :4
AIM : WAP Swap all odd and even bits/ Detecting Parity Bits, Generate all subsets of a given set
using bitwise operations.
PROGRAM :
#include <iostream>
#include <vector>
using namespace std;
8|P a g e
int main() {
// Part 1: Swap all odd and even bits
unsigned int n = 23; // Binary: 00010111
cout << "Original number: " << n << endl;
cout << "Number after swapping odd and even bits: " << swapOddEvenBits(n) <<
endl;
return 0;
}
OUTPUT :
9|P a g e
PROBLEM NO. :5
AIM : WAP to find the Kth largest elements in an array, Move all zeroes to end of array, Rearrange
array such that even positioned are greater than odd.
PROGRAM :
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
// Function to rearrange array such that even positioned elements are greater
than odd positioned elements
void rearrangeArray(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> result(nums.size());
int n = nums.size();
int left = 0, right = (n + 1) / 2;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
result[i] = nums[left++];
} else {
result[i] = nums[right++];
}
10 | P a g e
}
nums = result;
}
int main() {
// Example array
vector<int> arr = {3, 2, 1, 5, 6, 4, 0, 0, 3, 7};
// Part 3: Rearrange array such that even positioned elements are greater
than odd positioned elements
rearrangeArray(arr);
cout << "Array after rearrangement: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
return 0;
}
OUTPUT :
11 | P a g e
PROBLEM NO. :6
AIM : WAP to Rearrange an array in maximum minimum form using Two Pointer Technique,
Segregate even and odd numbers, Print All Distinct Elements of a given integer array.
PROGRAM :
#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;
12 | P a g e
void printDistinctElements(const vector<int>& arr) {
unordered_set<int> seen;
for (int num : arr) {
if (seen.find(num) == seen.end()) {
cout << num << " ";
seen.insert(num);
}
}
cout << endl;
}
int main() {
// Example array
vector<int> arr = {1, 3, 5, 2, 8, 7, 6, 4};
// Part 1: Rearrange in maximum minimum form
sort(arr.begin(), arr.end()); // Sort array first
rearrangeMaxMin(arr);
cout << "Array in maximum minimum form: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;
// Part 2: Segregate even and odd numbers
vector<int> arr2 = {12, 34, 45, 9, 8, 90, 3};
segregateEvenOdd(arr2);
cout << "Array after segregating even and odd numbers: ";
for (int num : arr2) {
cout << num << " ";
}
cout << endl;
// Part 3: Print all distinct elements of a given integer array
vector<int> arr3 = {4, 5, 4, 5, 6, 7, 8, 6, 7, 8};
cout << "Distinct elements in the array: ";
printDistinctElements(arr3);
return 0;
}
OUTPUT :
13 | P a g e
PROBLEM NO. :7
AIM : WAP to find sub-array with given sum, Reorder an array according to given indexes, Search an
element in a sorted and rotated array
PROGRAM :
#include <iostream>
#include <vector>
using namespace std;
// Function to find a sub-array with a given sum
bool findSubarrayWithGivenSum(vector<int>& arr, int sum) {
int current_sum = arr[0], start = 0;
for (int i = 1; i <= arr.size(); i++) {
while (current_sum > sum && start < i - 1) {
current_sum -= arr[start];
start++;
}
if (current_sum == sum) {
cout <<"Sub-array found from index "<< start <<" to "<< i – 1 <<endl;
return true;
}
if (i < arr.size()) {
current_sum += arr[i];
}
}
cout << "No sub-array with given sum found." << endl;
return false;
}
// Function to reorder an array according to given indexes
void reorderArray(vector<int>& arr, vector<int>& indexes) {
vector<int> temp(arr.size());
for (int i = 0; i < arr.size(); i++) {
temp[indexes[i]] = arr[i];
}
for (int i = 0; i < arr.size(); i++) {
arr[i] = temp[i];
}
}
// Function to search an element in a sorted and rotated array
int searchInSortedRotatedArray(vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
14 | P a g e
if (arr[left] <= arr[mid]) {
if (target >= arr[left] && target < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (target > arr[mid] && target <= arr[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
int main() {
// Part 1: Find sub-array with given sum
vector<int> arr1 = {1, 4, 20, 3, 10, 5};
int sum = 33;
findSubarrayWithGivenSum(arr1, sum);
// Part 2: Reorder an array according to given indexes
vector<int> arr2 = {50, 40, 70, 60, 90};
vector<int> indexes = {3, 0, 4, 1, 2};
reorderArray(arr2, indexes);
cout << "Reordered array: ";
for (int num : arr2) {
cout << num << " ";
}cout << endl;
// Part 3: Search an element in a sorted and rotated array
vector<int> arr3 = {4, 5, 6, 7, 0, 1, 2};
int target = 6;
int index = searchInSortedRotatedArray(arr3, target);
if (index != -1) {
cout << "Element " << target << " found at index " << index << endl;
} else {
cout << "Element " << target << " not found in the array." << endl;
}
return 0;
}
OUTPUT :
15 | P a g e
PROBLEM NO. :8
AIM : WAP to find the Rotation Count in Rotated Sorted array, Find the smallest missing number,
Merge two sorted arrays with O(1) extra space.
PROGRAM :
#include <iostream>
using namespace std;
16 | P a g e
arr1[j + 1] = arr1[j];
if (j != n - 2 || last > arr2[i]) {
arr1[j + 1] = arr2[i];
arr2[i] = last;
}
}
}
int main() {
// Rotation Count in Rotated Sorted Array
int arr[] = {7, 9, 11, 12, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Rotation count: " << rotationCount(arr, n) << endl;
OUTPUT :
17 | P a g e
PROBLEM NO. :9
AIM : WAP Mean of Array using Recursion, Sum of natural numbers using recursion, Decimal to
binary number using recursion.
PROGRAM :
#include <bits/stdc++.h>
using namespace std;
double arrayMean(const vector<int>& arr, int n, int sum = 0) {
if (n == 0)
return sum / static_cast<double>(arr.size());
else
return arrayMean(arr, n - 1, sum + arr[n - 1]);
}
int sumOfNaturalNumbers(int n) {
if (n == 0)
return 0;
else
return n + sumOfNaturalNumbers(n - 1);
}
long long decimalToBinary(int n) {
if (n == 0)
return 0;
else
return (n % 2) + 10 * decimalToBinary(n / 2);
}
int main() {
// Mean of Array using Recursion
vector<int> arr = {1, 2, 3, 4, 5};
cout << "Mean of array: " << arrayMean(arr, arr.size()) << endl;
// Sum of natural numbers using recursion
int n = 5;
cout<<"Sum of natural numbers up to"<< n<<": "<<sumOfNaturalNumbers(n)<<endl;
// Decimal to binary number using recursion
int decimal = 10;
cout<<"Binary representation of"<<decimal<<":"<<decimalToBinary(decimal)<<endl;
return 0;
}
OUTPUT :
18 | P a g e
PROBLEM NO. :10
AIM : Program for length of a string using recursion, Sum of digit of a number using recursion, Tail
recursion to calculate sum of array elements. Program to print first n Fibonacci Numbers
PROGRAM :
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
// Length of a string using recursion
string str = "Hello, world!";
19 | P a g e
cout << "Length of string: " << stringLength(str) << endl;
return 0;
}
OUTPUT :
20 | P a g e
PROBLEM NO. :11
AIM : WAP to Sort the Queue using Recursion, Reversing a queue using recursion, Delete a linked
list using recursion
PROGRAM :
#include <iostream>
#include <queue>
using namespace std;
// Move the elements smaller than pivot to left side of the queue and
// larger elements to right side using a pivot
int pivot = q.front();
q.pop();
queue<int> left, right;
while (!q.empty()) {
int curr = q.front();
q.pop();
21 | P a g e
if (curr < pivot)
left.push(curr);
else
right.push(curr);
}
int main() {
// Sorting a queue using recursion
queue<int> q;
q.push(5);
q.push(3);
q.push(7);
q.push(1);
cout << "Queue before sorting: ";
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
22 | P a g e
}
cout << endl;
q.push(5);
q.push(3);
q.push(7);
q.push(1);
sortQueue(q);
cout << "Queue after sorting: ";
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
cout << endl;
23 | P a g e
}
cout << endl;
deleteLinkedList(head);
cout << "Linked list after deletion: ";
if (!head)
cout << "Empty" << endl;
return 0;
}
OUTPUT :
24 | P a g e
PROBLEM NO. :12
AIM : WAP for Length of longest palindromic sub-string: Recursion, Program for Tower of Hanoi
Algorithm Find geometric sum of the series using recursion
PROGRAM :
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
if (str[start] == str[end])
return 2 + longestPalindromicSubstring(str, start + 1, end - 1);
else
return max(longestPalindromicSubstring(str, start, end - 1),
longestPalindromicSubstring(str, start + 1, end));
}
25 | P a g e
int main() {
// Length of the longest palindromic sub-string using recursion
string str = "abcbad";
cout << "Length of the longest palindromic sub-string: " <<
longestPalindromicSubstring(str, 0, str.length() - 1) << endl;
return 0;
}
OUTPUT :
26 | P a g e
PROBLEM NO. :13
AIM :WAP Problems related to Linear Search, Binary Search, Problems using Binary Search
PROGRAM :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
27 | P a g e
right = mid - 0.00001; // Accuracy up to 5 decimal places
}
return result;
}
// Problem using binary search: Find the peak element in an array
int findPeakElement(const vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1])
left = mid + 1;
else
right = mid;
}
return left;
}
int main() {
// Linear Search
vector<int> arr = {4, 2, 1, 5, 7, 3};
int targetLinear = 5;
cout << "Linear Search: Element " << targetLinear << " found at index " <<
linearSearch(arr, targetLinear) << endl;
// Binary Search
sort(arr.begin(), arr.end());
int targetBinary = 5;
cout << "Binary Search: Element " << targetBinary << " found at index " <<
binarySearch(arr, targetBinary) << endl;
OUTPUT :
28 | P a g e
PROBLEM NO. :14
PROGRAM :
#include <iostream>
#include <string>
using namespace std;
// Multiply the current result by 10 and add the integer value of the current
character
result = result * 10 + (str[index] - '0');
int main() {
string str = "12345";
int num = stringToInt(str);
cout << "String \"" << str << "\" converted to integer: " << num << endl;
return 0;
}
OUTPUT :
29 | P a g e
PROBLEM NO. :15
AIM : WAP Reverse a Doubly linked list using recursion, Check if a string is a scrambled form of
another string, N Queen Problem
PROGRAM :
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int n = s1.length();
for (int i = 1; i < n; ++i) {
30 | P a g e
if ((isScramble(s1.substr(0, i), s2.substr(0, i)) &&
isScramble(s1.substr(i), s2.substr(i))) ||
(isScramble(s1.substr(0, i), s2.substr(n - i)) &&
isScramble(s1.substr(i), s2.substr(0, n - i)))) {
memo[key] = true;
return true;
}
}
memo[key] = false;
return false;
}
31 | P a g e
void printBoard(const vector<vector<int>>& board) {
for (auto& row : board) {
for (int cell : row)
cout << cell << " ";
cout << endl;
}
}
void solveNQueens(int n) {
vector<vector<int>> board(n, vector<int>(n, 0));
if (solveNQueensUtil(board, 0, n))
printBoard(board);
else
cout << "No solution exists for N = " << n << endl;
}
int main() {
// Reverse a doubly linked list using recursion
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->prev = head;
head->next->next = new ListNode(3);
head->next->next->prev = head->next;
head->next->next->next = new ListNode(4);
head->next->next->next->prev = head->next->next;
cout << "Doubly linked list before reversal:" << endl;
ListNode* temp = head;
while (temp) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
head = reverseDoublyLinkedList(head);
cout << "Doubly linked list after reversal:" << endl;
temp = head;
while (temp) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl << endl;
32 | P a g e
cout << "Solutions for the N Queen Problem where N = 4:" << endl;
solveNQueens(4);
return 0;
}
OUTPUT :
33 | P a g e
PROBLEM NO. :16
PROGRAM :
#include <iostream>
#include <stack>
using namespace std;
34 | P a g e
if (s.empty())
return;
int x = s.top();
s.pop();
cout << x << " ";
printStack(s);
s.push(x);
}
int main() {
stack<int> s;
s.push(30);
s.push(20);
s.push(50);
s.push(40);
s.push(10);
sortStack(s);
return 0;
}
OUTPUT :
35 | P a g e
PROBLEM NO. :17
AIM : WAP to Sort elements by frequency, Sort an array of 0s, 1s and 2s, Sort numbers stored on
different machines
PROGRAM :
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<int> sortedArr;
for (const auto& p : freqVec) {
for (int i = 0; i < p.second; ++i) {
sortedArr.push_back(p.first);
}
}
return sortedArr;
}
36 | P a g e
// 2. Sort an array of 0s, 1s, and 2s (Dutch National Flag problem)
void sort012(vector<int>& arr) {
int low = 0, mid = 0, high = arr.size() - 1;
while (mid <= high) {
switch (arr[mid]) {
case 0:
swap(arr[low++], arr[mid++]);
break;
case 1:
mid++;
break;
case 2:
swap(arr[mid], arr[high--]);
break;
}
}
}
bool done;
do {
done = true;
int minValue = INT_MAX;
int minIndex = -1;
if (minIndex != -1) {
result.push_back(minValue);
indices[minIndex]++;
}
} while (!done);
return result;
37 | P a g e
}
int main() {
// 1. Sort elements by frequency
vector<int> arr1 = {5, 5, 4, 6, 4, 4, 6, 6, 6, 5, 7, 7, 7, 7};
cout << "Array sorted by frequency: ";
vector<int> sortedByFreq = sortByFrequency(arr1);
printVector(sortedByFreq);
return 0;
}
OUTPUT :
38 | P a g e
PROBLEM NO. :18
AIM : WAP for Sorting Strings using Bubble Sort, Sort even-placed elements in increasing and odd-
placed in decreasing order
PROGRAM :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
39 | P a g e
} else {
arr[i] = odd[k++];
}
}
}
// Utility function to print a vector of integers
void printVector(const vector<int>& vec) {
for (int val : vec) {
cout << val << " ";
}
cout << endl;
}
int main() {
// Sorting strings using bubble sort
vector<string> strArr = {"apple", "orange", "banana", "grape", "cherry"};
cout << "Strings before bubble sort: ";
printVector(strArr);
bubbleSort(strArr);
cout << "Strings after bubble sort: ";
printVector(strArr);
// Sorting even-placed elements in increasing and odd-placed elements in
decreasing order
vector<int> intArr = {10, 11, 20, 21, 30, 31, 40, 41};
cout << "Array before sorting: ";
printVector(intArr);
sortEvenOdd(intArr);
cout << "Array after sorting even-placed elements in increasing and odd-
placed elements in decreasing order: ";
printVector(intArr);
return 0;
}
OUTPUT :
40 | P a g e
PROBLEM NO. :19
AIM : WAP to Print array of strings in sorted order without copying one string into another. K-Way
Merge Sort
PROGRAM :
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
41 | P a g e
if (!sortedArrays[i].empty()) {
minHeap.push({sortedArrays[i][0], i});
}
}
vector<int> result;
// Extract the minimum element from the heap and add the next element from
the same array to the heap
while (!minHeap.empty()) {
auto [val, index] = minHeap.top();
minHeap.pop();
result.push_back(val);
return result;
}
int main() {
// Sorting strings using bubble sort without copying strings
vector<string> strArr = {"apple", "orange", "banana", "grape", "cherry"};
cout << "Original array of strings: ";
printStringVector(strArr);
42 | P a g e
// K-Way Merge Sort
vector<vector<int>> sortedArrays = {
{1, 5, 9},
{2, 6, 10},
{3, 7, 11},
{4, 8, 12}
};
return 0;
}
OUTPUT :
43 | P a g e
PROBLEM NO. :20
PROGRAM :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
44 | P a g e
// Recursively match the nuts and bolts
matchNutsAndBolts(nuts, bolts, low, pivot - 1);
matchNutsAndBolts(nuts, bolts, pivot + 1, high);
}
}
int main() {
vector<char> nuts = {'@', '#', '$', '%', '^', '&'};
vector<char> bolts = {'$', '%', '&', '^', '@', '#'};
return 0;
}
OUTPUT :
45 | P a g e