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
2using System;
3using System.Collections.Generic;
4
5public class Solution {
6 public IList<IList<int>> LargeGroupPositions(string s) {
7 List<IList<int>> result = new List<IList<int>>();
8 int start = 0;
9 for (int i = 1; i <= s.Length; i++) {
10 if (i == s.Length || s[i] != s[start]) {
11 if (i - start >= 3) {
12 result.Add(new List<int> { start, i - 1 });
13 }
14 start = i;
15 }
16 }
17 return result;
18 }
19}
20
The C# solution follows the same logic as the other implementations. It uses a list to collect intervals of large groups, appending them if a group meets the required size condition.
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`.