Salesforce OA Interview Question: Compression String Compression

48 Views
No Comments

Compression

To reduce the size of messages transmitted over the internet, a compression algorithm encodes consecutive repeating characters in a string.

Your task is to compress the given string using this rule:

  • Scan the string from left to right and group consecutive identical characters.
  • If a character appears once, add just the character to the output.
  • If a character appears more than once in a row, add the character followed by the number of consecutive occurrences.

Example

Suppose message = "aabbccca".

Output: a2b2c3a

Complete the compressedString function below.

The function is expected to return a STRING.

The function accepts STRING message as parameter.

Constraints

  • All characters in message are in the range ascii[a-z].
  • length of message <= 10^5

This problem asks you to run-length encode a lowercase string by compressing each maximal block of identical characters. A single character stays as-is, while repeated characters are written as the character plus its count. The key is a one-pass linear scan with a counter or two pointers, which produces an O(n) solution and works efficiently for strings up to 10^5 characters.

END
 0