FastPrepRun-Length Encode a String
Problem · String

Run-Length Encode a String

Learn this problem
EasyGoogle logoGoogleFULLTIMEPHONE SCREEN
See Google hiring insights

Problem statement

Given a string s, replace every maximal run of equal consecutive characters with the character followed by the run's decimal length.

Concatenate the encoded runs in their original order and return the resulting string. Return an empty string when s is empty.

Function

runLengthEncode(s: String) → String

Examples

Example 1

s = "aaabbc"return = "a3b2c1"

The maximal runs are aaa, bb, and c, with lengths 3, 2, and 1.

Example 2

s = "abcd"return = "a1b1c1d1"

Every character forms a run of length one.

Example 3

s = ""return = ""

There are no runs to encode.

Constraints

  • 0 <= s.length <= 200000
  • s contains lowercase English letters.

More Google problems

drafts saved locally
public String runLengthEncode(String s) {
    // Write your code here.
}
s"aaabbc"
expected"a3b2c1"
checking account