Multiple input and output in C++ - Time & Space Complexity
When a program takes several inputs and produces multiple outputs, it is important to see how the time it takes grows as these inputs get bigger.
We want to know how the total work changes when we have more inputs to handle.
Analyze the time complexity of the following code snippet.
#include <iostream>
using namespace std;
void process(int n, int m) {
for (int i = 0; i < n; i++) {
cout << i << " ";
}
cout << endl;
for (int j = 0; j < m; j++) {
cout << j*j << " ";
}
cout << endl;
}
int main() {
process(5, 3);
return 0;
}
This code prints numbers from 0 to n-1, then prints squares of numbers from 0 to m-1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two separate loops printing values.
- How many times: First loop runs n times, second loop runs m times.
Each loop runs independently, so total work is the sum of both.
| Input Size (n, m) | Approx. Operations |
|---|---|
| 10, 5 | 15 |
| 100, 50 | 150 |
| 1000, 500 | 1500 |
Pattern observation: The total steps grow roughly as the sum of n and m.
Time Complexity: O(n + m)
This means the time grows in a straight line with the size of both inputs added together.
[X] Wrong: "The time complexity is O(n * m) because there are two loops."
[OK] Correct: The loops run one after another, not inside each other, so their times add up, not multiply.
Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about efficiency in real situations.
"What if the second loop was placed inside the first loop? How would the time complexity change?"