PROBLEM LINK:
Practice
Contest: Division 3
Contest: Division 2
Contest: Division 1
Author: Jeevan Jyot Singh
Tester : Takuki Kurokawa
Editorialist: Aman Dwivedi
DIFFICULTY:
Simple
PREREQUISITES:
Palindromes
PROBLEM:
You need to construct the string of length N such that none of its substring of length \ge2 is a palindrome.
EXPLANATION:
Take any string of length 3 such that all the characters of this string are distinct. Now, just keep on repeating this string until you get the desired length N to get the desired string which is asked in the problem.
Why does this work?
Letâs say we have a string X of length 3 such that all the characters are distinct. That means:
Hence when we repeat this string we get:
- Observe that for any character, the character next to it and before to it is always different.
Now suppose we have generated the string of length N by repeating the string X. Now letâs consider any substring of length \ge2. Letâs say S[i, M] is the substring:
Now to be a palindromic substring the first and last character of this substring should be equal, letâs say :
-
S[i] = S[M]
-
Now can the characters S[i+1] and S[M-1] be the same ever. The answer is to this is NO as S[i] = S[M] and the characters next to it and before to it are always different.
Hence we can see there wonât be any palindromic substrings of length \ge2 in such construction.
TIME COMPLEXITY:
O(N) per test case
SOLUTIONS:
Author's Solution
Tester's Solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
string t = "tabr";
for (int i = 0; i < n; i++) {
cout << t[i % 4];
}
cout << '\n';
}
return 0;
}
Editorialist Solution
#include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin>>n;
string s="abc";
for(int i=0;i<n;i++)
cout<<s[i%3];
cout<<"\n";
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--)
solve();
return 0;
}