Skip to content

830. Positions of Large Groups 👍

  • Time: $O(|\texttt{S}|)$
  • Space: $O(|\texttt{S}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<vector<int>> largeGroupPositions(string S) {
    const int n = S.length();
    vector<vector<int>> ans;

    for (int i = 0, j = 0; i < n; i = j) {
      while (j < n && S[j] == S[i])
        ++j;
      if (j - i >= 3)
        ans.push_back({i, j - 1});
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public List<List<Integer>> largeGroupPositions(String S) {
    final int n = S.length();
    List<List<Integer>> ans = new ArrayList<>();

    for (int i = 0, j = 0; i < n; i = j) {
      while (j < n && S.charAt(j) == S.charAt(i))
        ++j;
      if (j - i >= 3)
        ans.add(Arrays.asList(i, j - 1));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def largeGroupPositions(self, S: str) -> List[List[int]]:
    n = len(S)
    ans = []
    i = 0
    j = 0

    while i < n:
      while j < n and S[j] == S[i]:
        j += 1
      if j - i >= 3:
        ans.append([i, j - 1])
      i = j

    return ans