yosen
yosen

Reputation: 61

The time complexity of Python's Loop

A Case

n = int(input())

for i in range(0,n):
    ...

B Case

n = int(input())

for i in range(0,n):
    for j in range(0, n):
        ...

C Case

n = int(input())

for i in range(0,n):
    ...
for j in range(0,n):
    ....

I was suddenly curious about Loop's time complexity.

I think A is O (n), B is O (n ^ 2), and C is O (n). is this right?

Is using an if statement in a for statement and using a for statement on the same line in case C fatal to memory?

Upvotes: 0

Views: 1116

Answers (1)

Anshuman Dikhit
Anshuman Dikhit

Reputation: 459

You are absolutely correct with regards to your analysis of the time complexity of each case (assuming there are only constant time operations within the for loops).

While I do not understand your second question, you refer to Case C, and I can say that there is nothing about that is "fatal to memory" within Case C. Hope this answered your question!

Upvotes: 1

Related Questions