1

for(int i=0; i<n; i++) { blah; } <== this has a complexity of O(n)

however if you know n to be 3 before hand won't the complexity become O(1), I mean i could just write out the instructions 3 times.

blah;
blah;
blah;

whereas if you don't know how big n is before you run the program then it's not possible to write down the instructions in the latter way.

Please clarify my misconception if I have it.

2
  • 2
    You pretty much explained it, what's the misconception? Commented Nov 25, 2013 at 13:06
  • 1
    @Operative the number of statements that u run increase linearly with n hence still O(n) even if you write it hard coded. Commented Nov 25, 2013 at 13:11

3 Answers 3

2

First of all the complexity of the first cycle is O(n * <complexity of blah>). Second this is assuming n is an input parameter to your algorithm. If n is a constant known beforehand than your estimation of O(<complexity of blah>) is correct.

Sign up to request clarification or add additional context in comments.

Comments

1

Time complexity of algorithms is only meaningful with regard to input size (n in your first example). If an algorithm receives no input such as blah; blah; blah;, then obviously its run time is going to be constant and independent of input size.

Comments

1

An algorithm has time complexity O(1), or O(n), or whatever, in the context of a sequence of inputs of increasing length. So to say something about the complexity, the algorithm must be able to accept arbitrarily long inputs. If you require that inputs are only of length 3, then it isn't meaningful to talk about the complexity of the algorithm.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.