Find Positions of Largest Groups of Characters in a String With Python

  • Home /
  • Blog Posts /
  • Find positions of largest groups of characters in a String with Python

The question

Take a string S of lowercase letters.

These letters form consecutive groupings of like characters.

Find groups with 3 or more like characters and return a list of lists of starting and ending index for each character group.

Elaboration and examples

If we show an example, we could say S = "abbcccdeffffy".

This string has 2 groups, c and f who’s consecutive characters are of 3 or more.

You need to return a list of lists with the starting and ending index, for the above example, this would be [[3,5],[8,11]]

Another example would be:

S = "nfjsaaaaaebbfbbbfennjheeeeej"

result = [[4,8],[13,15],[22,26]]

Writing some code

# Our function wrapper
def solveConsecutiveGroupIndexes(S):

    # store list of lists
    groups = []

    # keep track of loop item
    i = 0

    # loop through input string
    for j in range(len(S)):
        # if `is last item` or
        # `current item is not the same as next item`
        if j==len(S)-1 or S[j]!=S[j+1]:
            # if current string index minus loop index+1 is 3 or more
            if j-i+1 >= 3:
                # add start and end end index to groups
                groups.append([i, j])
            # increment next
            i = j+1

    # return result
    return groups