PROBLEM LINK:
Contest Division 1
Contest Division 2
Contest Division 3
Contest Division 4
Setter: Jeevan Jyot Singh
Tester: Nishank Suresh, Utkarsh Gupta
Editorialist: Pratiyush Mishra
DIFFICULTY:
2279
PREREQUISITES:
None
PROBLEM:
A string S is called good if none of the substrings of S of length \ge 2 are palindromic.
For e.g. S = \texttt{hello} is not good but S = \texttt{world} is good.
You are given a string A of length N (containing lowercase Latin letters only). Rearrange A to form a good string or determine it is not possible to do so.
Recall that a string is called palindromic if it reads the same backwards and forwards. For example, \texttt{noon} and \texttt{level} are palindromic strings.
EXPLANATION:
Observation: If in a string there are no palindromic sub-strings of length 2 or 3, then there are no palindromic sub-strings in the string(except for sub-strings of length 1).
Keeping this observation in mind, we divide the entire string into three containers c_1,c_2,c_3 where, c_i = \{j,\;such\;that\;j \;mod\; 3 = i, 1 \leq j \leq n\}. In order to avoid palindromic sub-strings of length 3, we must keep a distance of at least 2 between each same character or we must keep them in same containers. Thus for each character we have a limit of its frequency as:
If frequency of any character exceeds this limit then it won’t be possible to make it a good string.
Now let’s talk about the case when there are multiple characters that have frequency equal to limit. Taking another variable afford as (n \;mod\; 3).
- afford = 0: All containers are of length \lceil \frac{n}{3} \rceil.
- afford = 1: Only one container is of length \lceil \frac{n}{3} \rceil.
- afford = 2: Two containers are of length \lceil \frac{n}{3} \rceil.
Let us define bad as number of characters having frequency equal to limit. If bad is more than the number of containers having length equal to \lceil \frac{n}{3} \rceil, then it won’t be possible to construct a good string.
If none of such cases arise then we can confidently say that we can create a good string.
Now we loop through each characters in descending order of their frequency and if its frequency is equal to limit, then we fill it in all the positions of container whose size is equal to that of limit else we can fill its characters in the containers in the order c_3->c_2->c_1
TIME COMPLEXITY:
O(Nlog(N)), for each test case.
SOLUTION:
Editorialist’s Solution
Setter’s Solution
Tester1’s Solution
Tester2’s Solution