#830
Positions of Large Groups
EasyStringTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass through the string to identify groups of characters. By keeping track of the current character and its count, we can efficiently determine if a group is large and record its indices.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty list to store the intervals of large groups.
- 2Step 2: Loop through the string while keeping track of the current character and its count.
- 3Step 3: When the character changes, check if the count of the previous character is 3 or more.
- 4Step 4: If it is, record the start and end indices of that group.
- 5Step 5: Continue until the end of the string and return the list of intervals.
solution.py16 lines
1# Full working Python code
2
3def largeGroupPositions(s):
4 intervals = []
5 n = len(s)
6 count = 1
7 for i in range(1, n):
8 if s[i] == s[i - 1]:
9 count += 1
10 else:
11 if count >= 3:
12 intervals.append([i - count, i - 1])
13 count = 1
14 if count >= 3:
15 intervals.append([n - count, n - 1])
16 return intervalsℹ
Complexity note: The time complexity is O(n) because we make a single pass through the string, checking each character only once. The space complexity is O(n) in the worst case, where all characters are the same and form a large group.
- 1Identifying groups efficiently can reduce time complexity.
- 2Using a single pass to count characters minimizes overhead.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.