Everyone knows what run-length encoding is. It has been the subject of many code-golf challenges already. We'll be looking at a certain variation.


Normal: 11222222222222222222233333111111111112333322
Run-length: 112(19)3(5)1(11)2333322

The number in parentheses specifies the number of times the previous symbol occurred. In the example, only runs of 5 or more characters were encoded. This is because encoding runs of 4 or less doesn't improve the character count.


Write a function/program that implements this variation of run-length encoding, but can also encode runs of two symbols. The runs of two symbols must also be enclosed in parentheses. A group will also be enclosed in parentheses. Your program must accept a string as input, and output the modified string with modifications that shorten the string.


Normal: 111244411144411144411167676767222222277777222222277777123123123123
Double run-length: 1112((444111)(3))67676767((2(7)7(5))(2))123123123123


  • 111 was not encoded because encoding it (1(3)) is not shorter.
  • The string 444111 occurs 3 times so it is encoded.
  • 676767 was not encoded because ((67)(4)) is longer than before.
  • 222222277777222222277777 was not encoded as ((222222277777)(2)). Why? Because 222222277777 itself can be reduced to 2(7)7(5).
  • 123123123123 isn't encoded because your program is supposed to handle runs of two symbols, not three.

This is so shortest code wins. Tie-breaker is early submission.

If I missed anything, or if you are unsure of anything please notify me in the comments.

  • \$\begingroup\$ But there are 4 67s. \$\endgroup\$
    – Leaky Nun
    May 6, 2016 at 18:58
  • \$\begingroup\$ Will we have to handle 441444144414 -> ((4414)(3))? \$\endgroup\$
    – Leaky Nun
    May 6, 2016 at 18:58
  • \$\begingroup\$ I have fixed it. \$\endgroup\$
    – ericw31415
    May 6, 2016 at 18:59
  • \$\begingroup\$ @KennyLau No, you will not. 4414 is technically a series of 4. My wording is just bad. \$\endgroup\$
    – ericw31415
    May 6, 2016 at 18:59
  • \$\begingroup\$ Can 111111111 be encoded as (1)(9)? \$\endgroup\$ May 6, 2016 at 21:44

1 Answer 1


Retina, 162 bytes


Try it online!

  • \$\begingroup\$ If you input 10101010100100100100100, the output is ((10)(5))0((100)(4)), yet ((10)(4))((100)(5)) would be one character shorter. \$\endgroup\$
    – Marv
    May 8, 2016 at 1:38
  • \$\begingroup\$ Do you really have to use such marginal testcases.... \$\endgroup\$
    – Leaky Nun
    May 8, 2016 at 1:41
  • \$\begingroup\$ Yes, thats all the fun! :^) \$\endgroup\$
    – Marv
    May 8, 2016 at 1:46
  • \$\begingroup\$ It's funny how this is the only answer currently here. \$\endgroup\$
    – ericw31415
    May 23, 2016 at 23:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.