Skip to content

830. Positions of Large Groups 👍

  • Time: $O(n)$
  • Space: $O(n)$
 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