FastPrepBasic String Compression with Length Guard
Problems/Basic String Compression with Length Guard

Basic String Compression with Length Guard

New Relic logoNew Relic● EasyFULLTIMEPHONE SCREENONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report provides the core task and interview context. The callable signature, deterministic output order, examples, and bounds are source-faithful reconstruction details; estimated fidelity is 90%.

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

  • Longest Increasing Path in a MatrixPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
  • Product of Array Except SelfONSITE INTERVIEW · Seen Jul 2026
See New Relic hiring insights
Saved
class Solution {
    public String compressIfShorter(String text) {
        // write your code here
    }
}
Checking account…