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
2function largeGroupPositions(s) {
3 const result = [];
4 let start = 0;
5 for (let i = 1; i <= s.length; i++) {
6 if (i === s.length || s[i] !== s[start]) {
7 if (i - start >= 3) {
8 result.push([start, i - 1]);
9 }
10 start = i;
11 }
12 }
13 return result;
14}
15
The JavaScript version uses an array to store results, traversing the string in a loop. When a changing character or the end of the string is detected, the group size is checked to determine if it should be added to the results.
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
Using JavaScript and the two-pointer approach, this solution efficiently manages group detection and results appending based on character transitions identified by `fast`.