0
0
Cprogramming~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 several outputs, we want to know how the time it takes changes as the inputs grow.

We ask: How does the work increase when we have more inputs to handle?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

void process(int a[], int n, int b[], int m) {
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    for (int j = 0; j < m; j++) {
        printf("%d ", b[j]);
    }
}

int main() {
    int arr1[] = {1, 2, 3};
    int arr2[] = {4, 5};
    process(arr1, 3, arr2, 2);
    return 0;
}
    

This code prints all elements from two separate arrays, each with its own size.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Two separate loops printing elements of each array.
  • How many times: First loop runs n times, second loop runs m times.
How Execution Grows With Input

As the sizes of the two arrays grow, the total work grows by adding the work for each array.

Input Size (n, m)Approx. Operations
10, 5About 15 operations
100, 50About 150 operations
1000, 500About 1500 operations

Pattern observation: The total work grows roughly by adding the sizes of both inputs.

Final Time Complexity

Time Complexity: O(n + m)

This means the time grows in a straight line with the sum of both input sizes.

Common Mistake

[X] Wrong: "The time complexity is O(n * m) because there are two inputs."

[OK] Correct: The loops run one after another, not inside each other, so their times add, not multiply.

Interview Connect

Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about real problems with several parts.

Self-Check

"What if the two loops were nested instead of separate? How would the time complexity change?"