Suppose there is a string S of lowercase letters, these letters form consecutive groups of the same character. So, when a string like S is like "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy". A group will be a large group when it has 3 or more characters. We would like the starting and ending positions of every large group.
So, if the input is like "abcdddeeeeaabbbcd", then the output will be [[3,5],[6,9],[12,14]]
To solve this, we will follow these steps −
- ans := a new list
- csum := 0
- for each a, b in make group of letters with consecutive letters, do
- grp := the grouped item list
- if size of grp >= 3, then
- insert a list with (csum,csum + size of grp - 1) into ans
- csum := csum + size of grp
- return ans
Let us see the following implementation to get better understanding −
Example
from itertools import groupby class Solution: def largeGroupPositions(self, S): ans = [] csum = 0 for a, b in groupby(S): grp = list(b) if len(grp) >= 3: ans.append([csum, csum+len(grp)-1]) csum+=len(grp) return ans ob = Solution() print(ob.largeGroupPositions("abcdddeeeeaabbbcd"))
Input
"abcdddeeeeaabbbcd"
Output
[[3, 5], [6, 9], [12, 14]]