✏️ Explanatory Question

[Computational Complexity and Big-O Notation]

Consider the following snippet, calculate the time complexity:
double m = 1, n = 1;

for(int i = 0; i < x; i++)
{
    m *= Math.random();
}

for(int j = 0; j < y; j++)
{
    n *= Math.random();
}
    

👁 3 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Time Complexity = O(x + y)

Step-by-Step Analysis:

Loop 1:

for(int i = 0; i < x; i++)

This loop runs x times.

Each iteration performs a constant-time operation:

m *= Math.random();

So, time complexity of first loop:

O(x)

Loop 2:

for(int j = 0; j < y; j++)

This loop runs y times.

Each iteration is also constant time:

n *= Math.random();

So, time complexity of second loop:

O(y)

Important Observation:

  • Loops are independent (not nested)
  • They run one after another (sequentially)

Total Time Complexity:

O(x) + O(y) = O(x + y)

Key Rule:

Sequential loops → Add complexities Nested loops → Multiply complexities

Conclusion:

  • First loop → O(x)
  • Second loop → O(y)
  • Total → O(x + y)