Start learning free

LESSON 514 OF 639 · GREEDY

Partition Labels in Scala

Practice O(n)

You get a string s of lowercase letters.

Cut s into as many parts as you can. Return an ArrayBuffer with the size of each part, from left to right.

Each letter may appear in only one part. So if one part has an a, no other part can have one.

The parts keep the letters in order. Put back together, they give s again.

 

Example 1:

Input: s = "noonlevelradar"
Output: [4,5,5]
Explanation: The parts are "noon", "level" and "radar".
No letter shows up in two of them.
A cut inside "noon" would split its two n's.

Example 2:

Input: s = "mississippi"
Output: [1,10]
Explanation: The parts are "m" and "ississippi".
The m appears only once, so it is a part alone.
The first i is at index 1, and the last i is the final letter.
So "ississippi" can't be cut.

Example 3:

Input: s = "world"
Output: [1,1,1,1,1]
Explanation: Every letter appears once.
So each letter is a part of its own.

 

Constraints:

  • s has 1 to 100,000 letters.
  • Each letter is from a to z.

Note:

Your solution should run in O(n) time.

STEP 1 OF 12
    Ctrl + Enter to check

    Partition Labels in Scala

    Keep going with Scala500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free