Editorial for Facebook Hacker Cup '19 Final Round P1 - Strings as a Service
Submitting an official solution before solving the problem yourself is a bannable offence.
We need to generate any string of length at most which includes exactly some number of palindromes .
If our string features a substring consisting of copies of a single letter, then palindromes can be found within that substring. For example, AAA
includes palindromes ( copies of A
, copies of AA
, and 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 different letters for the substrings).
It may not be immediately obvious whether all values of up to may be satisfied with this approach without the string's length exceeding . However, if we consider the fact that every positive integer may be expressed as the sum of at most triangular numbers (numbers of the form , it becomes clear that this will do (based on the fact that , which in turn suggests a simple algorithm involving considering all feasible combinations of at most triangular numbers.
Two other simple approaches which require fewer letters (at most for any ) also exist. One option is to minimize the length of the string using standard dynamic programming (letting be the minimum length of a string of this form with exactly palindromes). The other involves greedily building the string by repeatedly using the longest substring which won't cause the palindrome count to exceed , which ends up never exceeding the minimum by more than character.
Comments