CS502 Assignment 1 Solution Fall 2024-1
CS502 Assignment 1 Solution Fall 2024-1
VUAnswer.pk
CS502 ASSIGNMENT 1 SOLUTION FALL 2024
Question 1
Consider the following piece of code of a function that processes a list of integers in the following
way:
You have to determine the time complexity of the given C++ code by analysing each line of the
code and also determine the overall time complexity of this code. You are required to show all
steps in detail.
Solution
We analyze each line or section of the code and assess its impact on the overall time complexity.
We'll use n to denote the size of the input list arr.
Step 1:
int n = arr.size(); // Step 1
This line simply assigns the size of the list arr to the variable n. Since determining the size of a
list in C++ is a constant-time operation, this line has a time complexity of O(1).
Step 2-3:
for (int i = 0; i < n; ++i) { // Step 2
std::cout << arr[i] << std::endl; // Step 3
}
This for loop iterates over each element of the list arr and prints it. Since the list has n elements,
this loop will run n times.
Step 4-7:
for (int j = 0; j < n; ++j) { // Step 4
for (int k = 0; k < n; ++k) { // Step 5
for (int l = 0; l < n; ++l) { // Step 6
std::cout << arr[j] * arr[k] * arr[l] << std::endl; // Step 7
}
}
}
Here, we have three nested loops. Each loop iterates over all n elements of the list arr.
Outer Loop (Step 4): Runs n times.
Middle Loop (Step 5): For each iteration of the outer loop, this loop also runs n times.
Inner Loop (Step 6): For each iteration of the middle loop, this loop also runs n times.
The total number of executions of Step 7 is the product of the iterations of each loop:
n×n×n=n3
Each execution of Step 7 takes O(1) time to compute the product and print the result, so the time
complexity of this section is O(n3)
REGARD - SARIM
WHATSAPP +923162965677
PLEASE NOTE:
Make sure you can make some changes to your solution file before
submitting copy paste solution will be marked zero.
If you found any mistake then correct yourself and inform me.
Before submitting an assignment must check your assignment requirement
file.
If you need some help or question about file and solutions feel free to ask.
VUAnswer.pk