All problems
0726MediumHash TableStringGreedy

Cutting The Bead Spool Into Clean Pieces

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2405Optimal Partition of String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A bead spool is threaded with one bead per position, and beads records their colours left to right, one lowercase letter per colour.

The spool has to be snipped into pieces. Each piece is a run of beads that were next to each other on the spool, every bead belongs to exactly one piece, and no piece may carry two beads of the same colour.

Return the smallest number of pieces the spool can be cut into.

Examples

Example 1

Input
beads = "gnome"
Output
1

No colour repeats anywhere on the spool, so the whole spool is already a clean piece.

Example 2

Input
beads = "cadbcbd"
Output
2

Cutting after the fourth bead gives the pieces `cadb` and `cbd`, and neither piece carries a colour twice.

Example 3

Input
beads = "wwww"
Output
4

Every bead is the same colour, so no piece can hold two of them and each bead ends up in a piece of its own.

Constraints

  • 1 <= beads.length <= 10^5
  • beads holds lowercase English letters only.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_segments(beads: str) -> int:
Java
public int fewestSegments(String beads)
September 7
Apply