In a string s of lowercase letters, a group is a consecutive run of the same character. A large group is defined as a group that has length >= 3.
Return the intervals [start, end] of every large group sorted in increasing order of start index.
1 <= s.length <= 1000s consists of lowercase English lettersUse the two-pointer technique to identify groups of consecutive identical characters and record intervals for groups with length >= 3.
Algorithm:
start pointer at index 0i from 1 to string lengthstart:
i - start[start, i-1]start = i for new groupThis approach works because:
Example Input: s = "abbxxxxzzy"
Step-by-step execution:
Result: [[3,6]]
class Solution {
public List<List<Integer>> largeGroupPositions(String s) {
List<List<Integer>> ans = new ArrayList<>();
int n = s.length();
int start = 0;
for (int i = 1; i <= n; i++) {
if (i == n || s.charAt(i) != s.charAt(start)) {
if (i - start >= 3) {
ans.add(Arrays.asList(start, i - 1));
}
start = i;
}
}
return ans;
}
}
class Solution {
public List<List<Integer>> largeGroupPositions(String s) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < s.length(); ) {
int j = i;
// Find end of current group
while (j < s.length() && s.charAt(j) == s.charAt(i)) {
j++;
}
// Check if group size >= 3
if (j - i >= 3) {
result.add(Arrays.asList(i, j - 1));
}
i = j;
}
return result;
}
}
Explanation: Use a single index that moves to find group boundaries.
Time Complexity: O(n) - still single pass, but slightly less efficient due to inner while loop Space Complexity: O(1) - constant extra space
class Solution {
public List<List<Integer>> largeGroupPositions(String s) {
List<List<Integer>> result = new ArrayList<>();
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("(.)\\1{2,}");
java.util.regex.Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
result.add(Arrays.asList(matcher.start(), matcher.end() - 1));
}
return result;
}
}
Explanation: Use regex to find sequences of 3 or more identical characters.
Time Complexity: O(n) - regex matching is generally O(n) Space Complexity: O(1) - excluding output list