r/javahelp • • Jan 04 '19

Solved When is a loop o(1)?

I'm super confused about when a for loop/while loop is o(1).

For instance if I have an array A= {1,2,3,4,5};

for(int i = 0; i< A.length; i++){
//append to string or something
}

This loop would be O(n) ? I understand if I loop: for(int i = 0; i< 100; i++){ //append to string or something }

This is constant time but when else is a loop constant time?

16 Upvotes

8 comments sorted by

View all comments

13

u/dkolion Jan 04 '19

Big O notation is a measure of complexity. A simplified way to look at it is how an algorithm grows/scales as a function of some input. In the first loop you provided, A is a parameter, with some length, which we call n. It stands to reason that as A grows, the running time of the loop will grow at the same rate. Because of this we say the loop is O(n), where n is the size of the array. In your second example, regardless of the size of the array (or any other input), we know that the loop will always run for exactly 100 iterations, in other words the runtime is constant with respect to the inputs, so it is O(1) complexity.