FastPrepBasic String Compression with Length Guard

Basic String Compression with Length Guard

New Relic logoNew Relic● EasyFULLTIMEPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Compress a string by replacing every maximal run of equal consecutive characters with the character followed by the run length in base 10.

Return the compressed representation only when it is strictly shorter than the original string. Otherwise, return the original string unchanged. The empty string remains empty.

Function

compressIfShorter(text: String) → String

Examples

Example 1

text = "aabcccccaaa"return = "a2b1c5a3"

The run encoding is a2b1c5a3, which is shorter.

Example 2

text = "abcdef"return = "abcdef"

The encoded form would be longer, so the original is returned.

Example 3

text = "aa"return = "aa"

a2 has the same length as the input, so the input is returned.

Constraints

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

More New Relic problems

See New Relic hiring insights
public String compressIfShorter(String text) {
    // write your code here
}
text"aabcccccaaa"
expected"a2b1c5a3"
Checking account…