Skip to content
Problem 830 · LeetCode 830(opens in a new tab)

Positions of Large Groups

EasyStrings

A string s of lower-case letters splits into groups: each group is a maximal stretch of one repeated letter. In "pqqrrrr" the groups are "p", "qq" and "rrrr".

Describe a group by the index of its first and last letter, both included. A group is large when it holds 3 or more letters. Return [start, end] for every large group, ordered by start.

Example 1

Input:  s = "abbbcdddd"
Output: [[1, 3], [5, 8]]
Why:    "bbb" sits at 1..3 and "dddd" at 5..8
2 more examples and the constraints

Example 2

Input:  s = "mmnn"
Output: []
Why:    both groups have only 2 letters

Example 3

Input:  s = "zzzzz"
Output: [[0, 4]]
Why:    the whole string is one group of 5

Constraints

  • 1 ≤ length of s ≤ 1,000
  • s holds lower-case English letters only

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Run-length list, then filterO(n)
  2. One pass with a start pointerO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 lettersVerdict
Run-length list, then filterO(n)
Clear; stores every run
One pass with a start pointerO(n)
Best; one pass, no extra list

n = length of s.

Edge cases to test

  • Large group at the end. "abccc" must return [[2, 4]]; close the group when i is the last index.
  • Whole string is one group. "zzzzz" gives [[0, 4]].
  • Exactly 3 letters. "xxx" counts: the rule is 3 or more, not more than 3.
  • No large group. "mmnn" or a single letter returns an empty list.
  • Same letter in two groups. "aaabaaa" has two separate large groups of 'a': [[0, 2], [4, 6]].

Common mistakes

  • Forgetting to close the final group, so a large group at the end is lost.
  • Using i − start as the size and missing groups of exactly 3.
  • Counting all copies of a letter in the string instead of one unbroken stretch.

How to talk through it

  1. 1Clarify. Is a group of exactly 3 large? Are the end indices inclusive? Must the output be sorted?
  2. 2Describe groups. A group is a maximal run of one letter; it ends where the next letter differs.
  3. 3Give the run-length idea. Compress into (letter, start, length), then filter the long ones.
  4. 4Drop the extra list. Track only start; close the group when the next letter differs or the string ends.
  5. 5Test out loud. Run "abccc", "zzzzz" and "mmnn" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?