Skip to main content
Back to problems
Leetcode
Medium
Strings
Arrays
Simulation
String Compression III

Compress a string by replacing each run of repeated characters with its length and character, while respecting a maximum run size per encoded chunk.

Acceptance 0%
Problem Statement

Problem

Given a string word consisting of lowercase English letters, compress it by scanning from left to right and grouping consecutive identical characters into runs.

For each run, split it into chunks of at most 9 characters. Each chunk is encoded as:

  • the chunk length as a digit
  • followed by the repeated character

Concatenate all encoded chunks in order to form the compressed string.

For example, a run of 12 'a' characters becomes 9a3a, because the run must be broken into chunks of size at most 9.

Return the compressed string.

Notes

  • The input is processed in order.
  • Each chunk length is always written as a single digit from 1 to 9.
  • Different runs are never merged, even if they use the same character.

Input Format

  • A single string word.

Output Format

  • Return a string representing the compressed form of word.

Constraints

  • 1 <= word.length
  • word contains only lowercase English letters.
  • Consecutive equal characters may appear in long runs.

Hints

  • Traverse the string once and count the length of each consecutive block.
  • Whenever a block reaches length 9, emit a chunk immediately and start a new chunk for the same character if needed.

Input Format

  • A single lowercase string word.

Output Format

  • Return the run-length encoded string using chunks of size at most 9.

Constraints

  • word contains only lowercase English letters.
  • Each encoded chunk uses one digit for the count, so the count per chunk is limited to 1 through 9.
Examples
Sample cases returned by the problem API.

Example 1

Input

word = "abc"

Output

"1a1b1c"

Explanation

Each character forms a run of length 1, so each is encoded as 1 followed by the character.

Example 2

Input

word = "aaaaaaaaaaaa"

Output

"9a3a"

Explanation

There are 12 consecutive a characters. Since each chunk can contain at most 9 characters, the run is split into 9a and 3a.

Show 1 more example

Example 3

Input

word = "aabcccccaaa"

Output

"2a1b5c3a"

Explanation

The runs are aa, b, ccccc, and aaa, which become 2a, 1b, 5c, and 3a respectively.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.