Search code examples
algorithmlanguage-agnosticpseudocode

Finding shortest repeating cycle in word?


I'm about to write a function which, would return me a shortest period of group of letters which would eventually create the given word.

For example word abkebabkebabkeb is created by repeated abkeb word. I would like to know, how efficiently analyze input word, to get the shortest period of characters creating input word.


Solution

  • O(n) solution. Assumes that the entire string must be covered. The key observation is that we generate the pattern and test it, but if we find something along the way that doesn't match, we must include the entire string that we already tested, so we don't have to reobserve those characters.

    def pattern(inputv):
        pattern_end =0
        for j in range(pattern_end+1,len(inputv)):
    
            pattern_dex = j%(pattern_end+1)
            if(inputv[pattern_dex] != inputv[j]):
    
                pattern_end = j;
                continue
    
            if(j == len(inputv)-1):
                print pattern_end
                return inputv[0:pattern_end+1];
        return inputv;