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

2

u/rzwitserloot Jan 04 '19

What you're missing is that big-O notation is always relative to some input (and another aspect of big-O is what it measures: time (CPU complexity/how long does it take; assume RAM access is completely free and there is infinite ram), or space (how much memory will the algorithm take to do its job). If a big-O notation doesn't say, generally, time is intended).

Take this code: int sum = 0; for (int i = 0; i < A.length; i++) sum += A[i]; – if you say that the A variable is an input to this code, then this code's time complexity is O(n) with respect to A's size, which means: If you double the input's size, you'd approximately double the time complexity. It's space complexity is O(1); even if A is many millions of entries, this code doesn't take more RAM.

But here: int sum = 0; for (int i = 0; i < 1000; i++) sum += A[i % A.length]; - which is code that sums the first 1000 entries of A, looping back to the start if A is smaller than that, this code's time complexity is O(1) relative to A's size: It doesn't matter how large A is, the amount of steps this code would take is about the same. If you want to, you could say that it is O(n) relative to the 1000 constant written directly into the source code: If someone were to make that number 10 times as large, your code would take about 10x longer to run: That's O(n).

So, when is a loop O(1)? When the # of times it runs is not dependent whatsoever on the input size.