Sponsored
Sponsored
This approach involves iterating through the string to detect groups of consecutive characters. We maintain a start index for the current group and check whenever a character changes. If the length of a group is 3 or more, we record the start and end indices.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n) for storing the result.
1
2import java.util.ArrayList;
3import java.util.List;
4
5public class Solution {
6 public List<List<Integer>> largeGroupPositions(String s) {
7 List<List<Integer>> result = new ArrayList<>();
8 int start = 0, n = s.length();
9 for (int i = 1; i <= n; ++i) {
10 if (i == n || s.charAt(i) != s.charAt(start)) {
11 if (i - start >= 3) {
12 result.add(List.of(start, i - 1));
13 }
14 start = i;
15 }
16 }
17 return result;
18 }
19}
20
The Java solution similarly uses a loop to traverse the string. As soon as a different character is encountered or we reach the end of the string, the length of the current group is checked. If the group is large enough, it is added to the result list.
The two-pointer technique is another efficient way to solve this problem. The idea is to have a slow pointer marking the start of the group and a fast pointer iterating through the string. When the character at the fast pointer changes or reaches the end, check the length of the group.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n) for storing the result.
1
This Java code leverages the two-pointer technique for efficient group detection and uses list operations to manage the groups and check their sizes.