r/javahelp • u/[deleted] • 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
4
u/Holothuroid Jan 04 '19
Is this a Java question or more general?
In general there are some operations that at second glance can be simplified. Like adding numbers from 1 to n. It's n(n+1)/2 according to little Gauss.