✏️ Explanatory Question

Question:

A student had written the following method to display “Hello World” four times:

void displayMessage()
{
    System.out.println("Hello World");
    System.out.println("Hello World");
    System.out.println("Hello World");
    System.out.println("Hello World");
}

Later, the student modified the code using a loop:

void displayMessage()
{
    int i = 1;
    while(i <= 4)
    {
        System.out.println("Hello World");
        i++;
    }
}

Compare the above code snippets with respect to time complexity.

👁 1 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Answer:

Both code snippets have the same time complexity: O(1).

Explanation:

In the first version:

  • The statement is executed exactly 4 times
  • The number of operations is fixed (constant)
  • Time complexity = O(1)

In the second version:

  • The loop runs from i = 1 to 4
  • Again, the loop runs exactly 4 times
  • The number of iterations is fixed, not dependent on input size
  • Time complexity = O(1)

Key Concept:

  • When the number of operations is fixed (independent of input), time complexity is constant → O(1)
  • Even though a loop is used, it still remains constant because the loop runs a fixed number of times

Conclusion:

  • Both implementations take constant time
  • The modified version improves code readability and reduces repetition
  • Time complexity remains unchanged → O(1)