Strings · Coding problem

Run-Length Compression

A free coding problem from the Run-Length Generation skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

Compress a string by replacing each maximal run of equal characters with the character followed by the run's length, but write the length only when it's more than 1.

Example

Input:  hhhoouuusse
Output: h3o2u3s2e
Input:  xyyyyyyyyyyyy
Output: xy12

Input format

One line containing s.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of lowercase English letters

How it's graded

  • Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in Run-Length Generation

Solve it Run-Length Compression free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime