0
0
C++programming~5 mins

Basic formatting in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Basic formatting
O(n)
Understanding Time Complexity

We want to see how the time a program takes changes as we give it more data.

For basic formatting, we ask: how does the program's work grow when formatting more items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

#include <iostream>
#include <vector>

void printNumbers(const std::vector<int>& nums) {
    for (int num : nums) {
        std::cout << "Number: " << num << std::endl;
    }
}

This code prints each number in a list with a label before it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the list.
  • How many times: Once for every number in the list.
How Execution Grows With Input

As the list gets bigger, the program prints more lines, so it takes more time.

Input Size (n)Approx. Operations
1010 print lines
100100 print lines
10001000 print lines

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of items to print.

Common Mistake

[X] Wrong: "Printing each item takes the same time no matter how many items there are."

[OK] Correct: Actually, printing each item adds up, so more items mean more total time.

Interview Connect

Understanding how loops affect time helps you explain how your code handles bigger data smoothly.

Self-Check

"What if we printed only every other number? How would the time complexity change?"