0% found this document useful (0 votes)
9 views5 pages

BSF2205007 Muhammad Ramzan Algo 06 Complexity

Uploaded by

mramzankhan413
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

BSF2205007 Muhammad Ramzan Algo 06 Complexity

Uploaded by

mramzankhan413
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

MUHAMMAD

RAMZAN
Roll No : Bsf2205007
Design and Analysis of Algorithm
ALGO NO:06.GIVEN AN ARRAY OF INTEGERS AND A TARGET SUM, FIND
TWO NUMBERS IN THE ARRAY THAT ADD UP TO THE TARGET. RETURN
THEIR INDICES.

CODE:

1. int main() {
2. int nums[] = {3,5,8,12};
3. int target = 13;
4. int n = sizeof(nums) / sizeof(nums[0]);
5. for (int i = 0; i < n; i++) {
6. for (int j = i + 1; j < n; j++) {
7. if (nums[i] + nums[j] == target) {
8. cout << "Indices: [" << i << ", " << j << "]" << endl;
9. return 0; } } }
10. cout << "No solution found." << endl;
11. return 0;
}
DRY RUN :
nums[] = {3, 5, 8, 12}

target = 13

n=4

Iteration 1:

i = 0, j = 1

nums[i] + nums[j] = 3 + 5 = 8 (not equal to 13)

Iteration 2

i = 0, j = 2

nums[i] + nums[j] = 3 + 8 = 11 (not equal to 13)

Iteration 3:

i = 0, j = 3

nums[i] + nums[j] = 3 + 12 = 15 (not equal to 13)

Iteration 4:

i = 1, j = 2

nums[i] + nums[j] = 5 + 8 = 13

Match found!Print: Indices: [1, 2]

Exit program

Output:Indices: [1, 2]
COMPLEXITY:
*Step 1: Initialization*
- `int nums[] = {3,5,8,12};` Complexity: O(1)
- `int target = 13;` Complexity: O(1)
- `int n = sizeof(nums) / sizeof(nums[0]);` Complexity: O(1)

*Total Complexity for Initialization: O(1)*


*Step 2: Outer Loop*
- `for (int I = 0; I < n; i++)` Complexity: O(n)

*Step 3: Inner Loop*

- `for (int j = I + 1; j < n; j++)` Complexity: O(n-1) ≈ O(n)

 *Total Complexity for Nested Loops: O(n) * O(n) = O(n^2)*


COMPLEXITY:
Step 4: Conditional Check & Printing*

- `if (nums[i] + nums[j] == target)` Complexity: O(1)


- `cout << “Indices: [“ << I << “, “ << j << “]” << endl;` Complexity: O(1)

*Total Complexity for Conditional Check & Printing: O(1)*

*Step 5: Returning*

- `return 0;` Complexity: O(1)


Total Complexity: O(1) + O(n^2) + O(1) = O(n^2)
 *Space Complexity: O(1)
 This algorithm’s time complexity is quadratic (O(n^2)) due to the nested loops, and its space complexity is
constant (O(1)).

You might also like