Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Two Pointers
String Compression

Compress a character array in place by replacing each run of repeated characters with the character followed by its count when the count is greater than 1.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

LeetCode 443

gfg
Problem Statement

String Compression

Given an array of characters, rewrite it in place so that consecutive repeated characters are replaced by the character followed by the number of repetitions.

For each group of the same character:

  • keep the character once,
  • append its count as decimal digits only if the count is greater than 1.

Return the new length of the compressed array.

The compression must use only constant extra space beyond the output write positions.

Input Format

  • A character array chars of length n.
  • The array contains printable characters, and repeated characters may appear in consecutive runs.

Treat the array as mutable and modify it in place.

Output Format

  • Return an integer: the length of the compressed array after rewriting it in place.
  • The first returned-length elements of chars should contain the compressed result.

Constraints

  • 1n20001 \le n \le 2000 for interview-style practice.
  • Use O(1)O(1) extra space.
  • Encode counts in base 10.
  • Counts may require multiple digits (for example, 12 becomes '1', '2').
Examples
Sample cases returned by the problem API.

Example 1

Input

chars = ['a','a','b','b','c','c','c']

Output

6

Explanation

The runs are aa, bb, and ccc, so the array becomes ['a','2','b','2','c','3'] and the new length is 6.

Example 2

Input

chars = ['a']

Output

1

Explanation

A single character stays as is, so the compressed array is ['a'].

Show 1 more example

Example 3

Input

chars = ['a','b','b','b','b','b','b','b','b','b','b','b']

Output

4

Explanation

The result is ['a','b','1','1'] because the run of b has length 11.

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.