0% found this document useful (0 votes)
8 views17 pages

LAB Assignment

The document contains multiple programming problems related to data structures and algorithms, including linked list reversal, binary tree traversal, binary search tree insertion, Huffman coding, quicksort, coin change problem, substring sum calculation, calorie expenditure, and shipping container optimization. Each problem is accompanied by code implementations in C++, input/output examples, and time and space complexity analyses. The problems aim to enhance understanding of fundamental concepts in computer science and algorithm design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

LAB Assignment

The document contains multiple programming problems related to data structures and algorithms, including linked list reversal, binary tree traversal, binary search tree insertion, Huffman coding, quicksort, coin change problem, substring sum calculation, calorie expenditure, and shipping container optimization. Each problem is accompanied by code implementations in C++, input/output examples, and time and space complexity analyses. The problems aim to enhance understanding of fundamental concepts in computer science and algorithm design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Problem 1:-Given the pointer to the head node of a linked list, change the next pointers of the

nodes so that their order is reversed. The head pointer given may be null meaning that the ini al
list is empty.

Code:-

#include <iostream> using

namespace std;

class SinglyLinkedListNode { public:

int data;

SinglyLinkedListNode* next;

SinglyLinkedListNode(int node_data) {

this->data = node_data; this->next

= nullptr;

};

class SinglyLinkedList { public:

SinglyLinkedListNode* head;

SinglyLinkedList() { this-

>head = nullptr;

void insertNode(int node_data) {

SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data);

if (!this->head) {

this->head = node;

} else {

SinglyLinkedListNode* temp = this->head;

while (temp->next != nullptr) {

temp = temp->next;

Sagandeep Assignment LAB


Singh | 22BCS14568
}

temp->next = node;

void printList(SinglyLinkedListNode* node) {

while (node != nullptr) { cout << node-

>data; node = node->next;

if (node) {

cout << "->";

cout << endl;

SinglyLinkedListNode* reverse(SinglyLinkedListNode* head) {

SinglyLinkedListNode* prev = nullptr;

SinglyLinkedListNode* curr = head;

SinglyLinkedListNode* next = nullptr;

while (curr != nullptr) { next = curr-

>next; curr->next = prev;

prev = curr; curr = next;

return prev;

};

int main() {

Sagandeep Assignment LAB


Singh | 22BCS14568
int t; cin

>> t; while

(t--) {

SinglyLinkedList* list = new SinglyLinkedList();

int n; cin >> n;

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

int data; cin >> data;

list->insertNode(data);

cout << "Original list: "; list-

>printList(list->head); list->head =

list->reverse(list->head); cout <<

"Reversed list: "; list->printList(list-

>head); delete list;

return 0;

Input:-

1234

Ouput:-

Original list: 1->2->3->4 Reversed

list: 4->3->2->1

Time Complexity:

• O(n) where n is the number of nodes in the linked list. The reverse func on iterates through
all the nodes once to reverse the pointers.

Space Complexity:

• O(1) as we are reversing the linked list in place without using any extra space other than a
few pointers (prev, curr, next).

Sagandeep Assignment LAB


Singh | 22BCS14568
Problem 2: Write the postOrder func on. It received 1 parameter: a pointer to the root of a binary
tree. It must print the values in the tree's postorder traversal as a single line of space-separated
values. Input Format Our test code passes the root node of a binary tree to the postOrder func on.

Constraints

Code:-

#include <iostream>

using namespace std;

class Node { public:

int data;

Node* le ;

Node* right;

Node(int value) {

data = value; le

= nullptr; right =

nullptr;

};

void postOrder(Node* root) {

if (root == nullptr) {

return;

postOrder(root->le );

postOrder(root->right); cout

<< root->data << " ";

int main() {

Sagandeep Assignment LAB


Singh | 22BCS14568
// Example tree crea on

Node* root = new Node(1);

root->le = new Node(2); root-

>right = new Node(3); root-

>le ->le = new Node(4); root-

>le ->right = new Node(5);

postOrder(root); return 0;

Input:-

/ \

2 3

/\

4 5

Output:-

45231

Time Complexity:

• O(n) where n is the number of nodes in the binary tree. Each node is visited once.

Space Complexity:

• O(h) where h is the height of the binary tree due to recursive func on calls. In the worst
case, the space complexity can go up to O(n) if the tree is skewed.

Problem 3: You are given a pointer to the root of a binary search tree and values to be inserted into
the tree. Insert the values into their appropriate posi on in the binary search tree and return the
root of the updated binary tree.

Code:-

#include <iostream>

using namespace std;

class Node { public:

Sagandeep Assignment LAB


Singh | 22BCS14568
int data;

Node* le ;

Node* right;

Node(int value) {

data = value; le

= nullptr; right =

nullptr;

};

Node* insert(Node* root, int data) {

if (root == nullptr) {

return new Node(data);

if (data < root->data) { root->le

= insert(root->le , data);

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

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

return root;

void inOrder(Node* root) {

if (root == nullptr) {

return;

inOrder(root->le );

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

inOrder(root->right);

Sagandeep Assignment LAB


Singh | 22BCS14568
}

int main() { Node* root = nullptr; int

n, data; cout << "Enter the number of

nodes: ";

cin >> n; for (int i = 0; i < n;

++i) { cout << "Enter node

value: "; cin >> data;

root = insert(root, data);

cout << "In-order traversal of the BST: ";

inOrder(root); cout << endl; return 0;

Input:-

Number of nodes: 5

Node values: 10 5 15 3 7

Output:-

In-order traversal of the BST: 3 5 7 10 15

Problem 4: Huffman Coding assigns variable length codewords to fixed length input characters
based on their frequencies. More frequent characters are assigned shorter codewords and less
frequent characters are assigned longer codewords.

Code:-

#include <iostream>

#include <string>

using namespace std;

class Node { public:

char data;

int freq;

Sagandeep Assignment LAB


Singh | 22BCS14568
Node* le ;

Node* right;

Node(char data, int freq) {

this->data = data; this-

>freq = freq; this->le =

nullptr; this->right =

nullptr;

};

void decode_huff(Node* root, string s) {

Node* current = root; for (int i = 0; i

< s.length(); i++) { if (s[i] == '0') {

current = current->le ;

} else { current =

current->right;

if (current->le == nullptr && current->right == nullptr) {

cout << current->data; current = root;

int main() {

Node* root = new Node('\0', 11); root->le = new

Node('A', 5); root->right = new Node('\0', 6); root-

>right->le = new Node('R', 2); root->right->right =

new Node('\0', 4); root->right->right->le = new

Node('\0', 2); root->right->right->right = new Node('B',

Sagandeep Assignment LAB


Singh | 22BCS14568
2); root->right->right->le ->le = new Node('C', 1);

root->right->right->le ->right = new Node('D', 1);

string encoded_string = "01111001100011010111100";

decode_huff(root, encoded_string); cout << endl;

return 0;

Input:-

01111001100011010111100

Output:-

ABRACADABRA

Time Complexity:

• O(n) where n is the length of the encoded string. We traverse the string once and for each
character in the encoded string, we traverse the tree.

Space Complexity:

• O(1) for decoding since no extra space is used other than the tree and the encoded string.

• O(h) for storing the Huffman tree, where h is the height of the tree. In the worst case, the
space complexity of the tree is O(n), where n is the number of unique characters.

Problem 5: we're covering a divide-and-conquer algorithm called Quicksort (also known as


Par on Sort). This challenge is a modified version of the algorithm that only addresses
par oning

Code:-

#include <iostream> #include <vector>

using namespace std; vector<int>

quickSort(vector<int> arr) { int pivot

= arr[0]; vector<int> le , equal,

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

if (arr[i] < pivot) {

le .push_back(arr[i]); } else if

Sagandeep Assignment LAB


Singh | 22BCS14568
(arr[i] == pivot) {

equal.push_back(arr[i]);

} else {

right.push_back(arr[i]);

vector<int> result; result.insert(result.end(),

le .begin(), le .end()); result.insert(result.end(),

equal.begin(), equal.end()); result.insert(result.end(),

right.begin(), right.end()); return result;

int main() {

int n; cin >> n;

vector<int> arr(n); for

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

cin >> arr[i];

vector<int> result = quickSort(arr);

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

cout << result[i] << " ";

cout << endl;

return 0;

Input:-

57438

Sagandeep Assignment LAB


Singh | 22BCS14568
Output:-

43578

Time Complexity:

• O(n): We iterate over the array once to par on the elements.

Space Complexity:

• O(n): We use three addi onal arrays (le , equal, and right) that can together
store all elements of the original array.

Problem 6: Given an amount and the denomina ons of coins available, determine how many ways
change can be made for amount. There is a limitless supply of each coin type.

Code:-

#include <iostream> #include <vector>

using namespace std; long long

getWays(int n, vector<int> c) {

vector<long long> dp(n + 1, 0); dp[0]

= 1; for (int coin : c) { for (int i =

coin; i <= n; i++) { dp[i] += dp[i -

coin];

return dp[n];

int main() { int n, m;

cin >> n >> m;

vector<int> coins(m);

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

cin >> coins[i];

Sagandeep Assignment LAB


Singh | 22BCS14568
cout << getWays(n, coins) << endl;

return 0;

Input:-

34

8312

Output:-

Problem 7. Samantha and Sam are playing a numbers game. Given a number as a string, no leading
zeros, determine the sum of all integer values of substrings of the string.

Code:-

#include <iostream> #include

<string> using namespace

std; const int MOD =

1000000007;

int substrings(string n) { long

long total_sum = 0; long long

current_sum = 0; long long

factor = 1; for (int i = n.size() - 1;

i >= 0; i--) { int digit = n[i] - '0';

current_sum = (current_sum + digit * factor) % MOD;

total_sum = (total_sum + current_sum) % MOD; factor

= (factor * 10 + 1) % MOD;

return total_sum;

Sagandeep Assignment LAB


Singh | 22BCS14568
int main() { string n; cin >>

n; cout << substrings(n) <<

endl; return 0;

Input:-

Input:

42

Output:

48

Problem 8: Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and
Marc can walk a distance to expend those calories. If Marc has eaten j cupcakes so far, a er ea ng
a cupcake with c calories he must walk at least 2i *c miles to maintain his weight.

Code:-

#include <iostream>

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

long marcsCakewalk(vector<int> calorie) { sort(calorie.rbegin(),

calorie.rend()); long totalMiles = 0; for (int i = 0; i <

calorie.size(); ++i) { totalMiles += (1 << i) * calorie[i]; // 2^i is

equivalent to (1 << i)

return totalMiles;

int main() {

int n; cin >> n;

vector<int> calorie(n);

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

cin >> calorie[i];

Sagandeep Assignment LAB


Singh | 22BCS14568
}

cout << marcsCakewalk(calorie) << endl; // Output the minimum miles

return 0;

Input: 3

5 10 7

Output:

44

Problem 9. Priyanka works for an interna onal toy company that ships by container. Her task is to
the determine the lowest cost way to combine her orders for shipping. She has a list of item
weights. The shipping company has a requirement that all items loaded in a container must weigh
less than or equal to 4 units plus the weight of the minimum weight item. All items mee ng that
requirement will be shipped in one container.

Code:-

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std; int

toys(vector<int> w) {

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

int containers = 0;

int n = w.size(); int i = 0; while (i <

n) { int minWeight = w[i]; int

maxWeight = minWeight + 4; while

(i < n && w[i] <= maxWeight) {

i++;

containers++; // Increment the container count

Sagandeep Assignment LAB


Singh | 22BCS14568
}

return containers;

int main() {

int n; cin >> n;

vector<int> weights(n);

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

weights[i]; // Weights of each order

cout << toys(weights) << endl;

return 0;

Input:

1 2 3 4 5 10 11 12 13

Output:

Problem 10. In this problem, we'll use the term "longest common substring" loosely. It refers to
substrings differing at some number or fewer characters when compared index by index. For
example, 'abc' and 'adc' differ in one posi on, 'aab' and 'aba' differ in two. Given two strings and
an integer k , determine the length of the longest common substrings of the two strings that differ
in no more than k posi ons.

Code:-

#include <iostream>

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

int substringDiff(int k, const string& s1, const string& s2) {

int maxLength = 0; int n1 = s1.size(); int n2 =

s2.size(); for (int i = 0; i < n1; i++) { for (int j = 0; j <

n2; j++) { int length = 0; int diffCount = 0;

Sagandeep Assignment LAB


Singh | 22BCS14568
while (i + length < n1 && j + length < n2) { if (s1[i

+ length] != s2[j + length]) { diffCount++;

if (diffCount > k) { break; //

Stop if differences exceed k

length++;

maxLength = max(maxLength, length);

return maxLength;

int main() {

int t; cin >> t; while (t--) { int k; string s1, s2;

cin >> k >> s1 >> s2; cout << substringDiff(k, s1, s2) << endl;

// Output the result

return 0;

Input:

1 abcd bbca

Output:

Time Complexity:

• O(n1 * n2 * min(n1, n2)): The nested loops result in checking every substring of both strings,
where n1 and n2 are the lengths of s1 and s2.

Sagandeep Assignment LAB


Singh | 22BCS14568
Space Complexity:

• O(1): We use a constant amount of extra space.

Sagandeep Assignment LAB


Singh | 22BCS14568

You might also like