Leetcode 830. Positions of Large Groups
The problem is as follows:
In a string s
of lowercase letters, a “large group” is a group that has 3 or more consecutive identical characters.
Write a function largeGroupPositions
that takes the string s
as input and returns the starting and ending positions of every large group in the string. The positions should be returned as a list of lists where each list contains two integers [start, end].
Example:
Input: s = "abbxxxxzzy"
Output: [[3, 6]]
Explanation: "xxxx" is the only large group with starting and ending positions [3, 6].
Input: s = "abc"
Output: []
Explanation: There are no large groups in the string.
Constraints:
s
contains lowercase English letters only.Here’s a possible implementation in C++:
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<vector<int>> largeGroupPositions(string s) {
vector<vector<int>> result;
int n = s.size();
int i = 0; // Initialize the starting pointer
while (i < n) {
int j = i;
// Move j to the end of the current group of same characters
while (j < n && s[j] == s[i]) {
j++;
}
// If the length of this group is 3 or more, add to result
if (j - i >= 3) {
result.push_back({i, j - 1});
}
// Move i to the next new character
i = j;
}
return result;
}
};
The time complexity of this solution is O(n), where n is the length of the string. Each character in the string is processed once, and operations inside the loop are constant time operations.
For s = "abbxxxxzzy"
, this implementation would produce the output [[3, 6]]
:
i = 0
: s[0] != s[1]
, so j = 1
. Move i
to 1
.i = 1
: s[1] == s[2] != s[3]
, j = 3
, i
to 3
.i = 3
: s[3] == s[4] == s[5] == s[6] != s[7]
, j = 7
, large group xxxx
from 3 to 6, add [3, 6]
to result, i
to 7
.If something is unclear or an edge case is missing, feel free to ask for further clarifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?