0
0
C++programming~5 mins

Multiple input and output in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multiple input and output
O(n + m)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each loop runs independently, so total work is the sum of both.

Input Size (n, m)Approx. Operations
10, 515
100, 50150
1000, 5001500

Pattern observation: The total steps grow roughly as the sum of n and m.

Final Time Complexity

Time Complexity: O(n + m)

This means the time grows in a straight line with the size of both inputs added together.

Common Mistake

[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.

Interview Connect

Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about efficiency in real situations.

Self-Check

"What if the second loop was placed inside the first loop? How would the time complexity change?"