Editorial for Facebook Hacker Cup '19 Final Round P1 - Strings as a Service


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

We need to generate any string of length at most 1000 which includes exactly some number of palindromes K.

If our string features a substring consisting of x copies of a single letter, then x (x+1) / 2 palindromes can be found within that substring. For example, AAA includes 6 palindromes (3 copies of A, 2 copies of AA, and 1 copy of AAA).

If we concatenate multiple such substrings together, then the total number of palindromes in the resulting string will be equal to the sum of palindrome counts within those substrings, plus any "additional palindromes" spanning multiple of the substrings. However, these additional palindromes can only exist if two substrings which are separated by at most one other substring feature the same letter. For example, additional palindromes exist in the concatenations AA + AA and AA + BB + AA, but not in the concatenation AA + BB + CC + AA.

We'll attempt to build a valid string out of such a concatenation, maintaining control over the exact palindrome count by ensuring that there are no additional palindromes (for example, by cycling through at least 3 different letters for the substrings).

It may not be immediately obvious whether all values of K up to 100\,000 may be satisfied with this approach without the string's length exceeding 1000. However, if we consider the fact that every positive integer may be expressed as the sum of at most 3 triangular numbers (numbers of the form x (x+1) / 2), it becomes clear that this will do (based on the fact that 3 * (333 * 334 / 2) > 100\,000), which in turn suggests a simple algorithm involving considering all feasible combinations of at most 3 triangular numbers.

Two other simple approaches which require fewer letters (at most 483 for any K) also exist. One option is to minimize the length of the string using standard dynamic programming (letting DP[p] be the minimum length of a string of this form with exactly p palindromes). The other involves greedily building the string by repeatedly using the longest substring which won't cause the palindrome count to exceed K, which ends up never exceeding the minimum by more than 1 character.


Comments

There are no comments at the moment.