0% found this document useful (0 votes)
16 views4 pages

Fall 2024 - CS502 - 1 - BC240205841

Assignment solution

Uploaded by

nayyabasghar13
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)
16 views4 pages

Fall 2024 - CS502 - 1 - BC240205841

Assignment solution

Uploaded by

nayyabasghar13
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/ 4

CS502- Fundamentals Of

Algorithms
Assignment #1 Fall-
2024
Nayyab Asghar
BC240205841

Question #1:
Consider the following piece of code of a
function that processes a list of integers in the
following way:
Int n = arr.size); // Step 1
/ First loop: print each element of the array for
(int I = 0; I <n; ++i){ // Step 2 std::cout <<
arr[i] << std::endl; // Step 3
/ Second nested loops: print the product of
each triplet of elements for (intj = 0;j <n; ++j)
{ // Step4 for (int k =0; k<n; ++k) { // Step 5
for (int l = 0;l<n; ++1){ // Step 6
Std::cout << arri]* arr[k]* arr1] <<
std::endl; // Step 7
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 #1:

1. First Loop (Single loop): Prints each element of the


array.
2. Second Part (Three nested loops): Prints the product
of every possible triplet of elements.

Step-by-Step Complexity Analysis

1. Initialization of `n` (`int n = arr.size();`)


- Time Complexity: O(1)

2. First Loop (`for (int I = 0; I < n; ++i)`)


- Operation: Printing each element once.
- Time Complexity: This loop iterates `n` times, so its
complexity is O(n).

3. Second Part (Three nested loops)


- Outer Loop (`for (int j = 0; j < n; ++j)`)
- Time Complexity of Outer Loop: O(n)
- Middle Loop (`for (int k = 0; k < n; ++k)`)
- Time Complexity of Middle Loop: O(n)
- Inner Loop(`for (int l = 0; l < n; ++l)`)
- Time Complexity of Inner Loop: O(n)
- Combined Complexity of Nested Loops: Since
each loop depends on `n` and they are nested, the total
complexity for this part is = O(n^3).

4. Printing Operation inside Nested Loops


- Each iteration of the inner loop executes a print
statement, which is O(1) in complexity.
- However, it is inside the (n^3) loop structure, so it
does not change the overall complexity.

Overall Time Complexity


- The first part (single loop) has a time complexity
of O(n)
- The second part (nested loops) has a time
complexity of O(n^3)

Since O(n^3) is the dominant term, the overall


time complexity of the code is (n^3).

You might also like