Skip to content

Commit 31560ec

Browse files
authored
Create 0830-positions-of-large-groups.java
1 parent fda6e8f commit 31560ec

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Title: Positions of Large Groups
3+
* LeetCode Link: https://leetcode.com/problems/positions-of-large-groups/
4+
*
5+
* Question Info:
6+
* In a string s of lowercase letters, a group is a consecutive run of the same character.
7+
* A large group is defined as a group that has length >= 3.
8+
* Return the intervals [start, end] of every large group sorted in increasing order of start index.
9+
*
10+
* Example:
11+
* Input: s = "abbxxxxzzy"
12+
* Output: [[3,6]]
13+
*
14+
* Approach:
15+
* - Use two pointers to track the start of a group and the current index.
16+
* - Iterate through the string from i = 1 to n.
17+
* - If we reach the end OR the current char differs from the start char:
18+
* - Check if the group length >= 3.
19+
* - If yes, record the interval [start, i-1].
20+
* - Move start = i to begin a new group.
21+
* - Return the list of all intervals.
22+
*
23+
* Dry Run (s = "abbxxxxzzy"):
24+
* i=1: s[1]='b', s[0]='a' => different, group size=1 (<3), skip, start=1
25+
* i=2: s[2]='b', s[1]='b' => same, continue
26+
* i=3: s[3]='x', s[1]='b' => different, group size=2 (<3), skip, start=3
27+
* i=4,5,6: still 'x', continue
28+
* i=7: s[7]='z', s[3]='x' => different, group size=4 (>=3), record [3,6], start=7
29+
* i=8: s[8]='z', s[7]='z' => same
30+
* i=9: s[9]='y', s[7]='z' => different, group size=2 (<3), skip, start=9
31+
* i=10: reached end, group size=1 (<3), skip.
32+
* Result: [[3,6]]
33+
*
34+
* Time Complexity: O(n), where n = length of string (single pass).
35+
* Space Complexity: O(1), ignoring output list.
36+
*/
37+
38+
class Solution {
39+
public List<List<Integer>> largeGroupPositions(String s) {
40+
List<List<Integer>> ans = new ArrayList<>();
41+
int n = s.length();
42+
int start = 0;
43+
44+
for (int i = 1; i <= n; i++) {
45+
if (i == n || s.charAt(i) != s.charAt(start)) {
46+
if (i - start >= 3) {
47+
ans.add(Arrays.asList(start, i - 1));
48+
}
49+
start = i;
50+
}
51+
}
52+
53+
return ans;
54+
}
55+
}

0 commit comments

Comments
 (0)