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

8

u/Alcool91 Jan 04 '19

In general a function is O(1) if the number of operations is constant with respect to its input. An example is a loop which always runs 5 times, computing the sum of the first five entries in an array. You can pass it an array as large as you want but the loop always runs 5 times. It does not scale with its input. 5 is always less than some constant multiple of 1 so we say it is O(1).

On the other hand, if you want to compute the sum of the every element in an array of n elements then you need to loop over the array and add each element to a running total, doing somewhere in the realm of n operations. If I pass in an array of 1000 elements then I have to do ~1000 operations whereas with the function above I still would only have to do 5 operations. Since in this case the number of operations we do scales linearly with the input we say it is O(n).