To find the index in a circular string that is formed starting from that index is first in lexicographic order

#include <stdio.h>
#include <string.h>


int findIndex(const char* str){

int ret = 0, i, j, k, l, len = strlen(str);

for(i = 1; i < len; ++i){

if(str[i] < str[ret]){

ret = i;

} else if(str[i] == str[ret]){

k = i;
l = ret;

for(j = 1; j < len; j++){

k = (k + j) % len;
l = (l + j) % len;


if(str[k] < str[l]){
ret = i;
break;
}
}
}
}

return ret;

}


int main() {

char *s = "ABCDEABCCDEA";

printf("%d\n", findIndex(s));
}
Advertisements

3 thoughts on “To find the index in a circular string that is formed starting from that index is first in lexicographic order

  1. for(j = 1; j < len; j++){ k = (k + j) % len; l = (l + j) % len; if(str[k] < str[l]){ ret = i; break; } }change this as:for(j = 1; j < len; j++){ k = (k + 1) % len; l = (l + 1) % len; if(str[k] < str[l]){ ret = i; break; } if(str[k]>str[l]) break; }then it'll work for all the inputs.

  2. This one line addition should fix it :)int findIndex(const char* str){ int ret = 0, i, j, k, l, len = strlen(str); for(i = 1; i < len; ++i){ if(str[i] < str[ret]){ ret = i; } else if(str[i] == str[ret]){ k = i; l = ret; for(j = 1; j < len; j++){ k = (k + j) % len; l = (l + j) % len; if(str[k] > str[l]) break; //The addition if(str[k] < str[l]){ ret = i; break; } } } } return ret;}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s