programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Problem regarding time complexity

Ranch Hand
Posts: 692
I was reading a book which tellls that the outer loops time complexity is O(n-m) whereas for inner loop the books gives explanation as

" The inner while
loop goes around at most m times, and potentially far less when the pattern match
fails. This, plus two other statements, lies within the outer for loop. The outer loop
goes around at most n−m times, since no complete alignment is possible once we
get too far to the right of the text. The time complexity of nested loops multiplies,
so this gives a worst-case running time of O((n − m)(m + 2)). "

Greenhorn
Posts: 3
Algorithm books like to be confusing. The for loop in your example will run n-m+1 times so that becomes the complexity and it'll be multiplied by the complexity of the inner loop. I'll try to demonstrate.

I'll use an example of two while loops because basically a while loop comes out to be the same thing as a for loop in time analysis.

Basically the time analysis on a while loop amounts to

twhile being the time of the while loop
tbody being the time of the body of the while loop
tcond being the time of the conditional of the while loop
"r" being how many times the body is to be run

The reason tcond is there at the end is because it will be ran again and become false at the end of loop.

So if you have loops inside of loops for instance:

Then we'll call the first while loop T1while and the second while loop T2while so T1 become