Leetcode 830. Positions of Large Groups
LeetCode Problem 830: Positions of Large Groups
In a string s
of lowercase letters, a “large group” is a group where three or more consecutive characters are the same.
Write a function that finds the start and end positions of every large group. The function should return a list of lists of integers where each list denotes the starting and ending positions (inclusive) of each large group, in the order of their occurrence in the string.
Example:
Input: s = "abbxxxxzzy"
Output: [[3,6]]
Input: s = "abc"
Output: []
Input: s = "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
i
and j
) to iterate through the string.i
at 0. Move j
until characters at i
and j
are the same.j
and i
.
i
) and end (j-1
) index of the group.i
to be at j
and continue the process until the end of the string is reached.import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> largeGroupPositions(String s) {
List<List<Integer>> result = new ArrayList<>();
int n = s.length();
int i = 0;
while (i < n) {
int j = i;
// Move j until we find a different character
while (j < n && s.charAt(j) == s.charAt(i)) {
j++;
}
// If length of the group is 3 or more
if (j - i >= 3) {
List<Integer> group = new ArrayList<>();
group.add(i);
group.add(j - 1);
result.add(group);
}
// Move i to j
i = j;
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
System.out.println(sol.largeGroupPositions("abbxxxxzzy")); // [[3, 6]]
System.out.println(sol.largeGroupPositions("abc")); // []
System.out.println(sol.largeGroupPositions("abcdddeeeeaabbbcd")); // [[3,5],[6,9],[12,14]]
}
}
n
is the length of the string s
. This is because each character is processed a constant number of times.With this strategy and code, the positions of large groups can be efficiently determined.
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?