FastPrepRun-Length Encoding

Run-Length Encoding

Zscaler logoZscaler● EasyINTERNONSITE INTERVIEW
Learn

Problem statement

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

For every run, append the run's character followed by the full run length in base 10. Include the count 1 for a singleton run.

Return the concatenated encoding. Return an empty string when text is empty.

Function

runLengthEncode(text: String) → String

Examples

Example 1

text = "aaabbccccd"return = "a3b2c4d1"

The runs are aaa, bb, cccc, and d. Every run contributes its count.

Example 2

text = ""return = ""

An empty input has no runs.

Example 3

text = "zzzzzzzzzzzzx"return = "z12x1"

The first run shows a multi-digit count, and the singleton x still contributes 1.

Constraints

  • 0 <= text.length <= 200000
  • text contains printable ASCII characters.

More Zscaler problems

See Zscaler hiring insights
public String runLengthEncode(String text) {
  // write your code here
}
text"aaabbccccd"
expected"a3b2c4d1"
Checking account…