ExamAdda Logo

String Compression

Medium

Given an array of characters chars, compress it in place using the following rules:

  • Consecutive repeating characters should be replaced with the character followed by its count.
  • If a character appears only once consecutively, keep only the character.
  • If the count is greater than 9, write each digit of the count separately.
  • Return the new length of the compressed array.

Modify the original array in place. Only the first k characters, where k is the returned length, are considered valid.

Example 1

Input

6
a a b b c c

Output

6
a2b2c2

Explanation

Each character appears twice consecutively, so each group is represented by the character followed by 2.

Example 2

Input

7
a a a b b b b

Output

4
a3b4

Explanation

a appears three times and b appears four times. The compressed array becomes a3b4.

Constraints

1 <= chars.length <= 2000
chars[i] is a lowercase English letter
uppercase English letter
digit
or symbol.

Hints:

Hint 1

Use one pointer to read each group of identical characters and another pointer to write the compressed result.

Hint 2

When a group contains more than one character, convert its count to a string and write each digit separately.

Author & Technical Reviewer

Chatla Jithin Sri Surya

Written by: Chatla Jithin Sri Surya

Chatla Jithin Sri Surya

Technically reviewed by: Chatla Jithin Sri Surya

Published

Nov 4, 2026

Last updated

Nov 4, 2026

Last technically reviewed

Nov 4, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output