I am trying to get an algorithm down to at least O(n^(3/2)) complexity. Here is the algorithm:
function( string s, int n )
{
bool result = false;
int position = 0;
for( int i = 0; i < n/2; i++ )
{
position = 0;
for( int j = i+1; j < n; j++ )
{
if( s[j] != s[position] ) break;
if( j == n ) result = true;
if( position == i ) position = 0;
else position++;
}
if(result) break;
}
return result;
}
The first for-loop will iterate n/2 times, which is O(n) complexity. I need to get the inside for-loop to be at most O(sqrt(n)), thus giving the entire algorithm a O(n^(3/2)) complexity. I am having difficulty trying to figure out if the nested for loop is the right complexity I need.
Note:
n is the size of the string. The function basically checks to see if a repeating pattern occurs in the string s. The only characters in s are "0" and "1". For example, if the string is "001001", then the pattern is "001" and occurs twice. The string is also even. That being said, syntax and functionally are irrelevant for this question. All basic actions are considered to take O(1) (constant) time, which is pretty much the entirety of this code.
Note2:
I am doing this for homework. But the homework question was just to get the algorithm working, which I have done. Getting the complexity down is just extra work to practise.
Any help or guidance would be appreciated!