# String Compression – HackerRank Solution

In this post, we will solve String Compression HackerRank Solution. This problem (String Compression) is a part of HackerRank Functional Programming series.

Contents

Joseph and Jane are making a contest for apes. During the process, they have to communicate frequently with each other. Since they are not completely human, they cannot speak properly. They have to transfer messages using postcards of small sizes.
To save space on the small postcards, they devise a string compression algorithm:

• If a character,Â ch, occursÂ n(> 1)Â times in a row, then it will be represented byÂ {ch}{n}, whereÂ {x}Â is the value ofÂ x. For example, if the substring is a sequence ofÂ Â 4a‘ (“aaaa“), it will be represented as “a4“.
• If a character,Â ch, occurs exactly one time in a row, then it will be simply represented asÂ {ch}. For example, if the substring isÂ “a”, then it will be represented asÂ “a”.

Help Joseph to compress a message,Â msg.

## Input

The only line of input contains a string,Â msg.

## Output

Print the stringÂ msgÂ as a compressed message.

## Constraints

• 1 <= length(msg) <= 105
• msgÂ consists of lowercase English characters (az) only.

Sample Input #00

``abcaaabbb``

Sample Output #00

``abca3b3``

Sample Input #01

``abcd``

Sample Output #01

``abcd``

Sample Input #02

``aaabaaaaccaaaaba``

Sample Output #02

``a3ba4c2a4ba``

Explanation

Sample Case #00: msg = “abcaaabbb”. Here, the firstÂ 3Â characters occur exactly once, and the rest of them occurÂ Â times in a sequence.

Sample Case #01: msg = “abcd“. As there is no multiple consecutive occurrence of any character, the compressed message will be same as original one.

Sample Case #02: msg = “aaabaaaaccaaaaba“. In the first 3 occurrences, ‘a‘ is repeatedÂ 4Â times, while in the last occurrence, there is only one ‘a‘. Also,’c‘ occurs two times, and ‘b‘ occurs one time in both occurrences.

## Solution – String Compression – HackerRank Solution

Scala

```import scala.io.StdIn

object Solution {
def main(args: Array[String]): Unit = {
case class Item(c: Char, count: Int)

.foldLeft(List[Item]()) {
case (Item(c, count) :: cs, next) if c == next => Item(c, count + 1) :: cs
case (list, next) => Item(next, 1) :: list
}
.map {
case Item(c, 1) => c.toString
case Item(c, n) => c.toString + n
}
.reduce((a, b) => b + a))
}
}
```

Note: This problem (String Compression) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.