0
0
C++programming~5 mins

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

Choose your learning style9 modes available
Time Complexity: String input and output
O(n)
Understanding Time Complexity

When working with strings in C++, it is important to understand how the time taken grows as the string size increases.

We want to know how reading and printing strings scales with their length.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <iostream>
#include <string>

int main() {
    std::string input;
    std::getline(std::cin, input);
    std::cout << input << std::endl;
    return 0;
}
    

This code reads a whole line of text from the user and then prints it back out.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Reading and printing each character of the string one by one internally.
  • How many times: Once for each character in the input string.
How Execution Grows With Input

As the input string gets longer, the program spends more time reading and printing each character.

Input Size (n)Approx. Operations
10About 10 character reads and 10 character writes
100About 100 character reads and 100 character writes
1000About 1000 character reads and 1000 character writes

Pattern observation: The work grows directly with the number of characters in the string.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows linearly with the length of the string.

Common Mistake

[X] Wrong: "Reading or printing a string is always a constant time operation."

[OK] Correct: Actually, the program must handle each character one by one, so longer strings take more time.

Interview Connect

Understanding how string input and output scale helps you reason about performance in many programs that handle text data.

Self-Check

"What if we used multiple strings and concatenated them before printing? How would the time complexity change?"