0% found this document useful (0 votes)
31 views12 pages

DAA Assignment

Uploaded by

aditya626622
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)
31 views12 pages

DAA Assignment

Uploaded by

aditya626622
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/ 12

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Subject: Design and Analysis of


Algorithms
Subject Code: 22CSH-311
Semester: 5th
Problem Type: Complex (Fast Learner)

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 initial list is
empty.
Example
head references the list 1->2->3->4->NULL
Manipulate the pointers of each node in place and return head, now referencing the head of
the list 3->2->1->NULL . Function Description Complete the reverse function.
reverse has the following parameter:
● SinglyLinkedListNode pointer head: a reference to the head of a list
Returns
● SinglyLinkedListNode pointer: a reference to the head of the reversed list Input

Format
The first line contains an integer t, the number of test cases.
Each test case has the following format:
The first line contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer, the data values of the elements in the linked list.
Constraints

Code:
public static SinglyLinkedListNode reverse(SinglyLinkedListNode llist) {
// Write your code here
if (llist == null)
return llist;

SinglyLinkedListNode current = llist;


SinglyLinkedListNode prev = null;

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

SinglyLinkedListNode next = null;

while (current != null) {


next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}
note: I have submitted my code in python language as java code was not getting accepted due to
site backend issue.
Output: 4 -> 3 -> 2 -> 1 -> NULL
Time Complexity: O(n)

Problem 2:
Write the postOrder function. 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 function. Constraints

Code:
public static void postOrder(Node root) {
if(root==null) return;

postOrder(root.left);

postOrder(root.right);
System.out.print(root.data+" ");
}
Output: 4 5 2 3 1
Time Complexity: O(n)

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 position in the binary search tree and return the
root of the updated binary tree.

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Input Format
You are given a function,
Node * insert (Node * root ,int data) {

}
Constraints
● No. of nodes in the tree<= 500
Code:
public static Node insert(Node root,int data) {
root = addRecursive(root, data);
return root;
}

public static Node addRecursive(Node current, int data) {


if(current == null) return new Node(data);
else {
if(current.data < data) {
current.right = addRecursive(current.right, data);
}
if(current.data > data) {
current.left = addRecursive(current.left, data);
}
}
return current;

}
Output: 2 3 4 6 7
Time Complexity: O(logn)

Problem 4:
Given an amount and the denominations of coins available, determine how many ways
change can be made for amount. There is a limitless supply of each coin type.
Example n =3 c = [8, 3, 1, 2]
There are 3 ways to make change for n =3: {1,1,1} ,{1,2} , and {3}.
Function Description
Complete the getWays function in the editor below.
Get Ways has the following parameter(s):
● int n: the amount to make change for
● int c[m]: the available coin denominations
Returns
● int: the number of ways to make change

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Input Format
The first line contains two space-separated integers n and m , where:
n is the amount to change m is
the number of coin types

The second line contains m space-separated integers that describe the values of each coin
type.
Constraints

Each c[i] is guaranteed to be distinct.


Hints
Solve overlapping subproblems using Dynamic Programming (DP):
You can solve this problem recursively but will not pass all the test cases without optimizing to
eliminate the overlapping subproblems. Think of a way to store and reference previously
computed solutions to avoid solving the same subproblem multiple times. * Consider the
degenerate cases:
- How many ways can you make change for > 0 cents? - How many ways can you make
change for >0 cents if you have no coins? * If you're having trouble defining your solutions
store, then think about it in terms of the base case (n=0). - The answer may be larger than a
32-bit integer.

Code:
public static long getWays(int n, List<Long> c) {
// Write your code here
int s = c.size();
long[][] ways = new long[s + 1][n + 1];
for(int i = 0; i <= s; i++){
ways[i][0] = 1;
}
for(int i = 1; i <= n; i++){
ways[0][i] = 0;
}
for(int i = 1; i <= s; i++){
for(int j = 1; j <= n; j++){
ways[i][j] = ways[i - 1][j];
int x = j - (int)(long)c.get(i - 1);
if(x >= 0)
ways[i][j] += ways[i][x];
}

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
}
return ways[s][n];
}
Output: 3
Time Complexity:O(n*m)

Problem 5:
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. All edges along the path to a character contain a
code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll
be a 1 (one). Only the leaves will contain a letter and its frequency count. All other nodes will
contain a null instead of a character, and the count of the frequency of all of it and its
descendant characters.
For instance, consider the string ABRACADABRA. There are a total of 11 characters in the string.
This number should match the count in the ultimately determined root of the tree. Our
frequencies are A= 5, B=2, R=2,C=1 and D-1. The two smallest frequencies are for C and D,
both equal to 1 , so we'll create a tree with them. The root node will contain the sum of the counts
of its descendants, in this case 1+1 =2 . The left node will be the first character encountered, C
, and the right will contain D . Next we have 3 items with a character count of 2 : the tree we
just created, the character B and the character R. The tree came first, so it will go on the left of
our new root node. B will go on the right. Repeat until the tree is complete, then fill in the 1 's
and 0 's for the edges. The finished graph looks like:

Input characters are only present in the leaves. Internal nodes have a character value of ϕ
(NULL). We can determine that our values for characters are:
A-0
B - 111
C - 1100
D - 1101 R - 10
Our Huffman encoded string is:

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

AB RAC AD AB RA
0 111 10 0 1100 0 1101 0 111 10 0 or
01111001100011010111100
To avoid ambiguity, Huffman encoding is a prefix free encoding technique. No codeword
appears as a prefix of any other codeword.
To decode the encoded string, follow the zeros and ones to a leaf and return the character there.
You are given pointer to the root of the Huffman tree and a binary coded string to decode.
You need to print the decoded string.
Function Description
Complete the function decode_huff in the editor below. It must return the decoded string.
decode_huff has the following parameters:
● root: a reference to the root node of the Huffman tree
● s: a Huffman encoded string
Input Format
There is one line of input containing the plain string, . Background code creates the Huffman
tree then passes the head node and the encoded string to the function.
Constraints

Code:
#include <iostream>
using namespace std;

class Node {
public:
char data;
Node* left;
Node* right;

Node(char data) {
this->data = data;
this->left = nullptr;
this->right = nullptr;
}
}
void decode_huff(Node* root, string s) {
Node* current = root;
for (char c : s) {
// Traverse the tree based on the input string

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

if (c == '0')
current = current->left;
} else {
current = current->right;
}

// If a leaf node is reached, output the character


if (current->left == nullptr && current->right == nullptr) {
cout << current->data;

current = root; // Reset to root for the next character


}
}
}

int main() {
// Create the Huffman tree
Node* root = new Node('\0');
root->left = new Node('A');
root->right = new Node('\0');
root->right->left = new Node('R');
root->right->right = new Node('\0');
root->right->right->left = new Node('\0');
root->right->right->left->left = new Node('C');
root->right->right->left->right = new Node('D');
root->right->right->right = new Node('B');

string encoded_string = "01111001100011010111100";

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

decode_huff(root, encoded_string); // Decode the encoded string


cout << endl;

// Clean up memory (optional but recommended)


delete root->left;
delete root->right->right->right; // Delete 'B'
delete root->right->right->left->right; // Delete 'D'
delete root->right->right->left->left; // Delete 'C'
delete root->right->right->left; // Delete '\0' left of 'D'
delete root->right->right; // Delete '\0' right of 'R'
delete root->right->left; // Delete 'R'
delete root->right; // Delete '\0' right of root
delete root; // Delete root

return 0;
}
Time Complexity: O(n)

Problem 5:
we're covering a divide-and-conquer algorithm called Quicksort (also known as Partition Sort).
This challenge is a modified version of the algorithm that only addresses partitioning. It is
implemented as follows:
Step 1: Divide
Choose some pivot element, p, and partition your unsorted array, arr, into three smaller
arrays: ,left ,right and equal, where each element in left < p, each element in right > p, and
each element in equal = p . Example
arr = {5,7,4,3,8}
In this challenge, the pivot will always be at arr[0], so the pivot is 5.
arr is divided into left = {4,3},equal = {5} , and right = {7,8}.
Putting them all together, you get {4,3,5,7,8} . There is a flexible checker that allows the
elements of left and right to be in any order. For example, {3,4,5,8,7} is valid as well. Given
arr and p =arr[0], partition arr into ,left, right and equal. using the Divide instructions above.
Return a 1-dimensional array containing each element in left first, followed by each element
in equal, followed by each element in right. Function Description
quickSort has the following parameter(s):
● int arr[narr[0] is the pivot element
Returns
● int[n]: an array of integers as described above

Input Format
The first line contains n, the size of arr .
The second line contains n space-separated integers arr[i] (the unsorted array). The first
integer,arr[0] , is the pivot element,p . Constraints

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

All elements are distinct.


Code:
#include <iostream> #include <vector> using
namespace std; vector<int>
quickSort(vector<int> arr) { int p = arr[0];
vector<int> left, equal, right; for (int i = 0; i <
arr.size(); i++) { if (arr[i] < p)
left.push_back(arr[i]); else if (arr[i] == p)
equal.push_back(arr[i]); else
right.push_back(arr[i]);
}
vector<int> result; result.insert(result.end(),
left.begin(), left.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> sortedArr = quickSort(arr);
for (int i = 0; i < sortedArr.size(); i++) {
cout << sortedArr[i] << " ";
} return
0;
}
Output: 4 3 5 7 8
Time Complexity : O(n)

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Problem 6:
Given an amount and the denominations of coins available, determine how many ways
change can be made for amount. There is a limitless supply of each coin type.
Example n =3 c = [8, 3, 1, 2]
There are 3 ways to make change for n =3: {1,1,1} ,{1,2} , and {3}.
Function Description
Complete the getWays function in the editor below.
getWays has the following parameter(s):
● int n: the amount to make change for
● int c[m]: the available coin denominations
Returns
● int: the number of ways to make change
Input Format
The first line contains two space-separated integers n and m , where:
n is the amount to change m is
the number of coin types

The second line contains m space-separated integers that describe the values of each coin
type.
Constraints

Each c[i] is guaranteed to be distinct.


Hints
Solve overlapping subproblems using Dynamic Programming (DP):
You can solve this problem recursively but will not pass all the test cases without optimizing to
eliminate the overlapping subproblems. Think of a way to store and reference previously
computed solutions to avoid solving the same subproblem multiple times. * Consider the
degenerate cases:
- How many ways can you make change for > 0 cents? - How many ways can you make
change for >0 cents if you have no coins? * If you're having trouble defining your solutions
store, then think about it in terms of the base case (n=0). - The answer may be larger than a
32-bit integer.

Code:
public static long getWays(int n, List<Long> c) {
// Write your code here
int s = c.size();
long[][] ways = new long[s + 1][n + 1];
for(int i = 0; i <= s; i++){
ways[i][0] = 1;

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
}
for(int i = 1; i <= n; i++){
ways[0][i] = 0;
}
for(int i = 1; i <= s; i++){
for(int j = 1; j <= n; j++){
ways[i][j] = ways[i - 1][j];
int x = j - (int)(long)c.get(i - 1);
if(x >= 0)
ways[i][j] += ways[i][x];
}
}

return ways[s][n];

Output: 3
Time Complexity:O(n*m)

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.
Given an integer as a string, sum all of its substrings cast as integers. As the number may become
large, return the value modulo 109 + 7.
Example
N = “42”
Here n is a string that has 3 integer substrings: 4,2, and 42. Their sum is 48, and 48 modulo (109
+ 7 ) = 48.
Function Description
Complete the substrings function in the editor below.
substrings has the following parameter(s):
● string n: the string representation of an integer
Returns
● int: the sum of the integer values of all substrings in n, modulo 109 + 7
Input Format
A single line containing an integer as a string, without leading zeros. Constraints

Code:

22BCS10116 Aditya Sharma


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
#include <iostream> #include
<string> using namespace
std; const int MOD = 1e9 + 7;
int substrings(string n) { long
long totalSum = 0; long long
factor = 1; long long
currentSum = 0;
for (int i = n.size() - 1; i >= 0; i--) {
currentSum = (currentSum + (n[i] - '0') * factor) % MOD;
totalSum = (totalSum + currentSum) % MOD; factor =
(factor * 10 + 1) % MOD;
} return
totalSum;
} int main() { string n; cin >> n;
cout << substrings(n) << endl;
return 0;
}

Output: 48
Time Complexity: O(n)

22BCS10116 Aditya Sharma

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy