Find positions of largest groups of characters in a String with Python

0 min read 195 words

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
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts