Positions of large groups

Question

In a string S of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".

Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.

The final answer should be in lexicographic order.

Example 1:

Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting  3 and ending positions 6.

Example 2:

Input: "abc"
Output: []
Explanation: We have "a","b" and "c" but no large group.

Example 3:

Input: "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]

Note:
1 <= S.length <= 1000

Solution

class Solution {
 public List < List < Integer >> largeGroupPositions(String S) {

  char[] charSArray = S.toCharArray();
  List < List < Integer >> result = new ArrayList < > ();
  int i = 0;
  int charCount = 1;

  while (i < S.length() - 1) {

   while (i < (S.length() - 1) && charSArray[i] == charSArray[i + 1]) {

    charCount += 1;
    i++;
   }

   if (charCount >= 3) {
    indexOfLargeGroup g = new indexOfLargeGroup();
    g.setIndex((i - charCount + 1), i);
    result.add(g.getIndex());
   }
   i++;
   charCount = 1;
  }

  return result;
 }

}

public class indexOfLargeGroup {

 private List < Integer > grpIndex = new ArrayList < > ();

 public void setIndex(int start, int end) {

  grpIndex.add(start);
  grpIndex.add(end);
 }

 public List < Integer > getIndex() {

  return grpIndex;
 }

}

Test Cases

  1. Input a string having only one large group and with exact char count=3 for eg. “xxx”.
  2. Input a string with no large group for eg. “abc”.
  3. Input a string with large group at the first index, last index and at the center for eg.“xxxabbyyccccccc”.
  4. Input an empty string.
  5. TODO: Input a null string (regression test, not handled in this code)
  6. Input a very large string, containing multiple large groups, of length 1000.
  7. Input a very large string, containing multiple large groups, of length > 1000.
  8. Input a string having repetitive characters but not in consecutive order for eg. “axxaaxyyyzz”.
  9. TODO Input a string with special characters forming like a large group(regression test, not handled in the code) for eg. “###@@@@aaaxxyybbbb”
  10. TODO Input a String with uppercase as repetition(regression test, not handled in the code) for eg. “AaaBbccc”.

See also