Problem · String

Run-Length String Compression

Learn this problem
EasyOracle logoOracleFULLTIMEONSITE INTERVIEW

Problem statement

Given a string text, encode each maximal run of equal consecutive characters from left to right.

  • Append the run's character once.
  • If the run length is greater than 1, append the full length in base 10.
  • If the run length is exactly 1, append no count.

Return the concatenation of all encoded runs. Return the empty string when text is empty.

Function

compressRuns(text: String) → String

Examples

Example 1

text = "aaabbccccd"return = "a3b2c4d"

The maximal runs are aaa, bb, cccc, and d. The singleton contributes only its character.

Example 2

text = ""return = ""

An empty input has no runs and produces an empty encoding.

Example 3

text = "zzzzzzzzzzzzx"return = "z12x"

The first run demonstrates a multi-digit count. The final singleton x has no count.

Constraints

  • 0 <= text.length <= 200000
  • text contains printable ASCII characters.
  • The returned encoding is formed exactly as specified; it does not need to be shorter than the input.

More Oracle problems

drafts saved locally
public String compressRuns(String text) {
  // write your code here
}
text"aaabbccccd"
expected"a3b2c4d"
checking account