Skip to main content
1 of 2
Fixed Point
  • 577
  • 4
  • 14

Given a string find the substring which repeats most often

Write a complete program (not just a function) which using stdin takes in a string of arbitrary length (assume string-length at least one) composed only of digits 0-9 and outputs using stdout the substring which repeats most often in the input string. The input string can be any length and the substring can be maximum half the length of the input string because it must repeat at least twice non-overlapping to be printed.

We following the following hierarchy selecting the substring to be printed.

  1. First priority, the longest substring
  2. Second priority, if we have multiple substrings of the same length, we pick the one repeating the most often.
  3. Third priority, if multiple substrings of the same size repeat the same number of times, pick the one which occurs first scanning from the left.

Here are some test cases followed by the rules and some explanation.

./myprogram 123456
No substrings repeat.

The substring must repeat more than once. If no substrings repeat the the output must exactly be the string "No substrings repeat." complete with the capitalization and the period.

./myprogram 12121
12

The sub-strings must not overlap. So in this case the largest repeating substring is 12 instead of 121.

./myprogram 99999999
9999

We want the largest substring which repeats twice. Here 9, 99, 999, and 9999 all repeat at least twice. But we want the largest substring which repeats at least twice.

./myprogram 321321788788788
788

321, 788, 887, and 878 each repeat so pick we pick 788 which repeats the most often.

./myprogram 12121
12

12 and 21 both repeat twice so we pick 12 which occurs first from the left.

./myprogram 12012112299999999
9999

The string 12 occurs first and repeats thrice but 9999 is longer and repeats only twice so we pick 9999 because it has the highest priority.

./myprogram 56698853211564788954126162561664412355899990001212345
412

No substrings of length more than three repeat. 412, 616, and 123 each repeat twice. 412 occurs first and is thus printed.

I think I have taken care of all the cases. True code-golf. The shortest code in any language wins. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks and probably longer. So the community please feel free to upvote any solutions you like. The cleverness/beauty of the code matters much more than who posts first.

Happy coding!

Fixed Point
  • 577
  • 4
  • 14