We are asked to compute the minimal number of changes to letters such that the resulting string contains no palindrome substrings of length > 1. In other words, any substring of length >= 2 should not be a palindrome. This includes even-length palindromes (like "aa" length 2) and odd-length palindromes (like "aba" length 3). So essentially we need to avoid any palindrome substring of length 2 or more.
Given constraints: total length across test cases <= 1e5, t <= 1e5.
Goal: For each string s, output minimal changes to achieve a string with no palindromes of length >=2.
We need to compute minimal edits to break all palindromes.
Observation: The condition "no palindrome substrings of length > 1" is quite restrictive. Let's explore what strings satisfy that.
We need to avoid:
-
Palindromes of length 2: s[i] == s[i+1] for any i.
-
Palindromes of length 3: s[i] == s[i+2] for any i.
-
Palindromes of length 4: s[i] == s[i+3] and s[i+1] == s[i+2]? Actually a palindrome of length 4 requires s[i] == s[i+3] and s[i+1] == s[i+2]. But if we already avoid length 2 and length 3, does that guarantee no longer palindromes? Possibly not: e.g., "abcba" length 5 would have s[0]==s[4] and s[1]==s[3] and middle is whatever. But if we avoid length 3, that ensures no s[i]==s[i+2], which is necessary for odd-length >=5? Actually for odd-length palindrome, the center is a character, and condition includes that characters at symmetric positions are equal. For length 5: positions i,i+4 and i+1,i+3. The condition i+1,i+3 is distance 2, so if we forbid s[j] == s[j+2] for all j, then that condition fails. Also for even-length palindrome length 4: condition i,i+3 is distance 3, and i+1,i+2 distance 1. The distance 1 condition is length 2 palindrome? Actually i+1,i+2 being equal would be a length-2 palindrome. So if we forbid length-2 palindromes, we forbid s[i+1]==s[i+2]. So forbidding length 2 and length 3 palindromes might be sufficient to forbid all longer palindromes? Let's check.
Consider palindrome of length 5: positions i,i+4 and i+1,i+3. The condition i+1,i+3 implies distance 2 -> a length 3 palindrome (centered at i+2). So if we avoid any length 3 palindrome (i.e., no s[j]==s[j+2]), then we cannot have that. For palindrome of length 4: conditions s[i]==s[i+3] and s[i+1]==s[i+2]. The condition s[i+1]==s[i+2] is a length-2 palindrome. So if we avoid length 2 palindromes, that condition fails. So indeed, if a string has no palindrome of length 2 or length 3, then it cannot have any palindrome of length >=4? Let's reason more formally.
Lemma: If a string contains a palindrome of length L >= 4, then it contains a palindrome of length 2 or 3.
Proof: Suppose we have a palindrome of length L. Consider its first two characters and last two characters. If L is even: L=2k. Then the palindrome is s[i..i+2k-1] with s[i+j]==s[i+2k-1-j] for j=0..2k-1. In particular, for j=k-1 and k? Actually we need to find a shorter palindrome inside. The standard property: any palindrome of length >3 contains a palindrome of length 2 or 3 as a substring? Not exactly: e.g., "abcba" length 5 contains "bcb" length 3, which is a palindrome. And "abccba" length 6 contains "cc" length 2? Actually "abccba" contains "cc" at positions 2,3 (if indexed from 0?), check: s = a b c c b a. There is "cc" at positions 2-3, which is length 2 palindrome. So yes, any palindrome length >=4 must contain either a length-2 or length-3 palindrome. More rigorous: For any palindrome of length L>=4, consider the first two characters: s[i] and s[i+1]. Their symmetric counterparts are s[i+L-1] and s[i+L-2]. The palindrome condition gives s[i+1] = s[i+L-2]. If s[i] == s[i+1], then we have length-2 palindrome at i,i+1. If not, then we have s[i] != s[i+1]. But we can also look at the three-character prefix: s[i], s[i+1], s[i+2]. Their symmetric counterparts: s[i+L-1], s[i+L-2], s[i+L-3]. The palindrome condition gives s[i] = s[i+L-1], s[i+1] = s[i+L-2], s[i+2] = s[i+L-3]. Now if s[i+1] == s[i+2]? That's not directly guaranteed. But consider the substring of length 3 starting at i: s[i],s[i+1],s[i+2]. If s[i] == s[i+2] then that's a palindrome of length 3. Is it possible that a palindrome of length >=4 has no length-2 or length-3 palindrome? Suppose L=4: s = a b b a? Actually a b b a has "bb" length 2. a b a b? That's not palindrome. For palindrome length 4, it must satisfy s[0]==s[3] and s[1]==s[2]. So s[1]==s[2] is length-2 palindrome. So any palindrome length 4 has a length-2 palindrome (the middle two are equal). For palindrome length 5: s = a b c b a. The substring s[1..3] = b c b is a palindrome length 3. So yes. For length 6: s = a b c c b a. substring s[2..3] = c c length 2. More generally, in any palindrome of length >=4, either there is an inner pair of equal adjacent characters or there is an inner character with symmetric equal neighbors at distance 1? We can check length 7: a b c d c b a. The substring from index 2 to 4: c d c is length 3 palindrome. So indeed, any palindrome of length >=4 contains a palindrome of length 2 or 3. This is because the palindrome's interior (excluding the outer characters) is a palindrome of length L-2, and by induction eventually we reach length 2 or 3. More directly: If L is even, then the center consists of two adjacent characters which must be equal (since they are symmetric). So there is a length-2 palindrome. If L is odd, then the center three characters form a palindrome of length 3 (the center character plus the two symmetric ones). So any palindrome length >=4 contains either a length-2 palindrome (if even) or length-3 palindrome (if odd). Therefore, the condition of having no palindrome substring of length >1 is equivalent to having no palindrome of length 2 and no palindrome of length 3. Because if we eliminate all length-2 and length-3 palindromes, then automatically no longer palindromes can exist. (We also need to ensure length-1 palindromes are allowed; they are trivial.)
Thus we need to modify the string so that for all i: s[i] != s[i+1] (no adjacent equal), and for all i: s[i] != s[i+2] (no distance-2 equal). That's the condition.
So the problem reduces to: Given a string, we can change characters at cost 1 per change, want to achieve a string with no adjacent equal and no equal at distance 2. Minimize total changes.
We need to compute minimal number of changes needed.
Since we can change letters arbitrarily, the problem is like editing the string to satisfy these two constraints.
Constraints: For any three consecutive positions i, i+1, i+2, we must have s[i] != s[i+1] and s[i] != s[i+2] and also s[i+1] != s[i+2]? Wait, condition s[i+1] != s[i+2] is also required because adjacent equality (i+1, i+2) would be a palindrome of length 2. So we need all adjacent pairs distinct. So indeed for every adjacent pair, letters must differ. And also for every two positions with distance 2, letters must differ.
So for any three consecutive indices i, i+1, i+2, we require that all three letters are pairwise distinct? Let's check: Conditions: s[i] != s[i+1] (adjacent), s[i+1] != s[i+2] (adjacent), and s[i] != s[i+2] (distance 2). So yes, any three consecutive positions must have three distinct letters. That is a stronger condition: three consecutive letters all different.
But is that condition sufficient for the whole string? If every three consecutive are all distinct, then obviously adjacent all different and distance-2 all different. So the entire string must be such that no two positions with distance 1 or 2 are equal.
This is reminiscent of constructing a string over alphabet with constraints: For any i, s[i] != s[i-1] and s[i] != s[i-2] (for i>=2). That's like a constraint graph that is a path with edges for distance 1 and 2. Equivalent to a string with no two identical letters within a distance of 2. That's like a "3-ary" constraint: each position cannot be equal to the previous two letters.
Thus we need to transform the given string into one that satisfies that constraint, with minimal changes.
Now, since total length across test cases up to 1e5, we need an O(n) or O(n * something small) per test case.
We can think of dynamic programming on positions, with state representing the last two characters (or the values at i-1 and i-2) because the constraint only depends on previous two letters. However, the alphabet size is 26, which is small. But DP with 2626 states per position might be O(n * 26^2) = O(676n) which is acceptable for n total 1e5? 1e5 * 676 ≈ 67.6 million, which is borderline but maybe okay in C++ with optimizations? However t up to 1e5, but total length 1e5, so n average 1, but worst-case one test of length 1e5. 67.6 million is okay (since 1e8 operations might be okay in 2 seconds? Usually 10^8 simple operations borderline but likely pass given optimized code). But we can do better: use DP with 2626 but we can prune to only consider possible characters for each position? Actually we can use DP to compute minimal changes to reach a state (a,b) at position i (meaning s[i-1]=a, s[i]=b, and the prefix up to i satisfies constraints). We'll iterate positions from 2 to n-1? Let's design.
We have string s of length n. We'll process from left to right, but the constraint involves two previous letters. So we can define dp[i][x][y] = minimal changes needed to make prefix up to position i (0-indexed) such that the character at position i-1 is x and at position i is y (with i>=1). However the cost incurred includes changes at positions up to i. We can compute transition to next position i+1: choose a character z for position i+1 such that z != y (adjacent) and z != x (distance 2). Then dp[i+1][y][z] = min(dp[i+1][y][z], dp[i][x][y] + (z != original s[i+1])). Initialize with first two positions? But careful: For i=0, we have only one character, constraints for positions 0 and 1? The condition for distance 2 only applies when there are three positions. So for positions 0 and 1, only condition is s[0] != s[1] (if n>=2). So we need to handle base cases appropriately.
Alternatively, we can treat DP with i from 0 to n-1, state being the previous character and the character before that. Since constraints only involve up to distance 2, DP with 26*26 states works.
Complexity: O(n * 26 * 26 * 26) if we iterate over all possible z for each state? Actually transition from state (x,y) to choose z (26 possibilities) check if z != x and z != y, then compute cost. That is O(26^3) per position? Because for each state (x,y) (26*26), we loop over z (26). That would be 26^3 = 17576 per position. That's too much: 1e5 * 17576 = 1.7576e9, not acceptable.
But we can optimize: we don't need to iterate over all states for each position; we can do DP where we maintain dp[y][z] after processing up to i. Then to add a new character w, we need to consider previous state (x,y) but x is the character before y. However, we can store dp for current index i (as the last character) and also the second last. Actually we can use dp[i][last][second_last]? That is same. The naive transition from dp[i][x][y] to dp[i+1][y][z] would be O(26^3) if we iterate over all (x,y,z). However we can reduce to O(26^2) per position by noting that for each (y,z) we want the minimum over x such that x != z, of dp[i-1][x][y] (where dp[i-1][x][y] is cost up to i-1 with last two characters x,y, and i is current? Let's define properly.
Let positions indexed 0..n-1. We want to compute minimal changes.
Define f(i, a, b) = minimal changes to transform the prefix s[0..i] such that s[i-1] = a and s[i] = b, where i >= 1. For i=1, we only have positions 0 and 1, with condition a (s[0]) and b (s[1]) must be distinct (if n>=2). For i=0, we can define base.
Then for i >= 1, to extend to i+1 with character c (s[i+1]), we need c != b (adjacent) and c != a (distance 2). Then f(i+1, b, c) = min over (a,b) of f(i, a, b) + cost(c) where cost(c) = 0 if c == original s[i+1] else 1.
So for each i, we need to update dp for new pairs (b,c). For each (b,c) that satisfy b != c, we need to consider the best previous state (a,b) with the additional constraint a != c. So we need to compute, for each b, the minimum of f(i, a, b) over all a such that a != c (and also a != b? Actually a and b already satisfy constraints: for state (a,b) to be valid at i, we must have a != b (since they are adjacent positions i-1 and i) and also if i>=2, we would have ensured a != previous before a? That's captured recursively. But in the DP we only store states that are valid. So we maintain dp[a][b] valid only if a != b.
Then for each b and c with b != c, we compute new_dp[b][c] = min_{a: a != c} (dp[a][b]) + cost(c). Also need to ensure that a != b already from dp validity, but we also must enforce that a != c (the distance 2 constraint). So essentially we need, for each b, the minimum dp[a][b] over all a, and also the second minimum perhaps to handle the a != c constraint. Because when we choose c, we cannot take a that equals c. So for each fixed b, we can precompute the minimum value over all a (a != b) and also which a gives that minimum; also second minimum (with a different character) to handle the case where the minimum's a equals c, then we need the next best where a != c.
Thus we can update in O(26^2) per position: for each b (26), compute the min and second min of dp[a][b] over a (a != b). But careful: dp[a][b] includes only states where a != b. That's fine. Then for each c (26) with c != b, new_dp[b][c] = (if best_a for b is not equal to c then min_val else second_min_val) + cost(c). Also we must consider that maybe there is only one valid a? But alphabet 26, there will be at least 25 a's for given b (since a can be any except b). So there is always at least one a. So we can compute min and second min.
But we also need to incorporate cost for the original character at position i+1. So for each b and c we compute cost = (c != s[i+1] ? 1 : 0). Then new_dp[b][c] = best_prev + cost.
Thus per position we do: For each b (26) compute min and second min among dp[a][b] for a in 0..25, a != b. That's O(2626) = 676 per position. Then for each b, iterate c (26) such that c != b (25 values), compute best_prev, which is O(2625) ≈ 650 per position. So total per position O(26^2) ~ 676, which times 1e5 = 67.6 million, similar to earlier but now more efficient than 17576. This should be fine.
We also need to handle the base cases for i=0 and i=1.
Let's outline DP details:
Let n = len(s). If n == 1, answer is 0 because no palindromes of length >1.
If n >= 2, we will compute DP for positions up to n-1.
We'll index from 0.
We define dp[a][b] for the current pair being (a,b) at positions i-1 and i, after processing up to i. We'll initialize for i=1: after processing first two characters (positions 0 and 1). We'll set dp[a][b] = cost for positions 0 and 1 to be a and b respectively, but only if a != b (since they must be different to avoid palindrome length 2). cost = (a != s[0]?1:0) + (b != s[1]?1:0). We'll compute this for all 26*26 pairs with a != b.
Then for each next position i from 2 to n-1 (i is index of new character), we compute new_dp of size 26x26 (but only store where b != c? Actually new_dp will represent pair (b,c) with b != c and also ensure the distance-2 constraint with a? That will be enforced by transition). We'll compute new_dp as described.
After processing all positions, answer is min over dp[a][b] (for the last two positions) of dp[a][b] (since condition satisfied up to end). But note: if n == 2, we just take min over dp[a][b] from initialization.
We must also consider that constraints for distance-2 only apply when there are three characters. So for n==2, only condition is a!=b. Our DP covers that.
Edge cases: n=0 not possible.
Complexities: DP arrays of size 26x26 = 676, constant.
Now is that sufficient? Let's test with examples.
Example 1: "babba". length 5.
Our DP should output 1.
We'll test manually maybe later.
But we need to be cautious: Are we sure that eliminating length-2 and length-3 palindromes is equivalent to no palindrome >1? As argued, yes. However, need to be certain: What about palindrome of length exactly 4? It requires both a length-2 palindrome (middle two) and outer equal. So if we remove length-2 palindrome, then no length-4 palindrome can exist because the middle two must be equal. But what if we remove length-2 palindrome by ensuring no adjacent equal, then length-4 palindrome impossible. Similarly length-5 requires a length-3 palindrome; if no length-3, then impossible. And for longer, induction. So condition holds.
Thus DP solves.
But maybe there is a simpler greedy? Let's think: The constraints are local: each position cannot be equal to previous two letters. This is similar to a graph coloring on a path with distance-2 constraints. The minimal number of changes to achieve a valid string is like we want to find a valid string (over 26 letters) with minimum Hamming distance to original. This is a classic DP with small alphabet, as above.
But we can also consider that since alphabet size (26) is larger than the maximum degree of constraints (2), we can always find a valid character for each position without conflict, given that we can change. However we want to minimize changes, so we want to choose characters that match original as much as possible subject to constraints.
This is essentially a constrained sequence alignment problem which can be solved via DP.
Given that 26 is small, DP is fine.
But we must be careful about memory and speed. Since total sum length 1e5, DP per position O(26^2) = 676 operations, which yields about 67.6 million, which is fine in C++.
However, we can further optimize by noting that we can limit transitions to only characters that are relevant? But not needed.
Let's detail DP steps:
Let idx(c) = c - 'a', map letters to 0..25.
Initialize if n >= 2:
Let INF = large number (e.g., 1e9).
Initialize dp[26][26] with INF.
For a in 0..25:
for b in 0..25:
if a == b: continue
cost = (a != s0) + (b != s1)
dp[a][b] = cost
Then for i = 2 to n-1:
orig = s[i] - 'a'
// Precompute for each b, min1[b] = minimal dp[a][b] over a != b, and the character a that achieves it (min_char). Also min2[b] = second minimal value over a != b and a != min_char.
For b in 0..25:
min1 = INF, min2 = INF
min_char = -1
for a in 0..25:
if a == b: continue
val = dp[a][b]
if val < min1:
min2 = min1
min1 = val
min_char = a
elif val < min2:
min2 = val
store min1[b], min2[b], min_char[b].
// Now compute new_dp[26][26] filled INF
For b in 0..25:
for c in 0..25:
if b == c: continue
// best previous value for extending with c after b
// we need min over a != c of dp[a][b]
best = (min_char[b] != c) ? min1[b] : min2[b]
// ensure best is finite (should be)
cost_add = (c != orig) ? 1 : 0
new_dp[b][c] = best + cost_add
// replace dp with new_dp
After loop, answer = min_{a,b, a!=b} dp[a][b] (but dp only stored for a!=b because we never set when a==b, and we never produce a==b because we skip b==c; also ensure new_dp only for b!=c; also dp after initialization only for a!=b. So all entries considered are valid.
If n == 1: answer = 0.
Edge case n == 0 not possible.
Check for n == 2: after initialization we take min dp[a][b]. That yields minimal changes to make first two characters distinct. That's correct: if original s[0]==s[1], we need at least 1 change; else 0. For example "aa" -> need 1 change. But note: For "aa", any change to one letter to something else, e.g., "ab", cost 1. So answer 1. In example they have "a" length 1 -> 0.
Now test with sample.
We'll simulate mentally maybe not necessary.
But I want to verify that DP indeed captures constraints correctly. For positions i-1 and i we have state (a,b) with a!=b. When extending to i+1 with c, we require c != b and c != a. The DP transition ensures c != b (since we skip when b==c) and ensures a != c via picking best among a that are not equal to c. However, we need to guarantee that the state we are extending from had already satisfied all constraints for earlier positions, which it does. So after adding c, the new triple (a,b,c) has all distinct. But note: The constraint also requires that at position i+1, it must not equal the character at i-1? That's the a != c condition. Yes.
Now what about constraints for earlier triples? They are satisfied because we only extend from valid states.
Thus DP yields minimal changes.
Complexities okay.
But wait: The DP state we maintain at each step is for the last two characters of the prefix. However, do we need to also consider the character before those two? For the next step, the constraint only uses the last two. So it's a Markov property. So DP is correct.
Now consider a potential improvement: we could do a greedy algorithm? However, due to the constraints being local, DP is optimal.
Now, but is there any nuance? The original problem statement said "substring palindrome" defined as deleting from beginning and end, i.e., contiguous substring. So indeed our equivalence is correct. But let's double-check: A substring is contiguous? Usually "substring" is contiguous. However the definition: "A string a is a substring of a string b if a can be obtained from b by deleting several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end." That's indeed the definition of a contiguous substring. So yes.
Thus, we need to avoid palindromes that are contiguous substrings of length >=2.
Hence DP works.
But there's a catch: Are we sure that avoiding palindromes of length 2 and 3 ensures no longer palindromes? For odd lengths, the palindrome of length 5 has center three characters forming palindrome length 3. But that center three is a substring, so it would be a palindrome of length 3. So if we forbid all length 3 palindromes, no odd length >=5 can exist. For even lengths, the palindrome of length 4 includes a length-2 palindrome (the middle two). So forbidding length 2 palindromes prevents even length >=4. So indeed.
Now consider palindrome of length 0 or 1: trivial.
Thus condition is exactly as we described.
Now we should implement.
Implementation details:
-
We'll read t, then for each test case read string s.
-
n = s.length().
-
if n == 1: print 0; continue.
-
Convert s to array of ints (0-25).
-
Initialize dp as 2D vector (26 x 26) with INF. Could use array<array<int,26>,26> for speed.
-
For a in 0..25:
for b in 0..25:
if a != b:
cost = (a != s[0]) + (b != s[1])
dp[a][b] = cost
-
For i from 2 to n-1:
orig = s[i]
// compute mins
int min1[26], min2[26], minChar[26];
for b in 0..25:
int m1 = INF, m2 = INF, c1 = -1;
for a in 0..25:
if a == b: continue;
int v = dp[a][b];
if (v < m1):
m2 = m1; m1 = v; c1 = a;
else if (v < m2):
m2 = v;
min1[b] = m1; min2[b] = m2; minChar[b] = c1;
// new_dp
array<array<int,26>,26> new_dp;
// set all to INF
for b in 0..25:
for c in 0..25:
new_dp[b][c] = INF;
for b in 0..25:
for c in 0..25:
if b == c: continue;
int best = (minChar[b] != c) ? min1[b] : min2[b];
// ensure best not INF; but should be finite because there is at least one a.
if (best >= INF) continue; // though not needed.
int cost = (c != orig) ? 1 : 0;
new_dp[b][c] = best + cost;
dp = new_dp;
-
answer = INF;
-
for a in 0..25:
for b in 0..25:
if a != b:
if dp[a][b] < answer: answer = dp[a][b];
-
print answer.
Check edge: n=2: we skip loop for i>=2, then answer from dp directly.
But note: For n=2, is it necessary to enforce that first two are distinct? Yes, because palindrome "aa" length 2 is not allowed. So dp only contains states with a!=b, and we take min. So correct.
Now, we need to be careful: For n=0? Not.
Now, we should test with sample.
But before coding, let's think about potential simplification: Could we treat it as a minimum vertex cover or something? Probably not needed.
Now test sample manually.
Input:
7
babba
abaac
codeforces
zeroorez
abcdcba
bbbbbbb
a
We'll run mental small checks.
Test 1: "babba" length5.
We can compute answer expected 1.
Let's try to see DP might yield 1.
Maybe I'll simulate quickly with code mental? Not necessary.
But to be safe, we can test conceptually: Original string: b a b b a.
We need to avoid adjacent equal and distance-2 equal.
Check adjacent: positions: 0-1: b,a ok; 1-2: a,b ok; 2-3: b,b not ok; 3-4: b,a ok. So problem at 2-3.
Distance-2: check positions 0-2: b,b equal -> not ok (palindrome "bab"? Actually "bab" is length3 palindrome). So both constraints violated.
Minimum changes? Perhaps change position 2 from b to something else, e.g., c, yields b a c b a. Check: adj: b a ok, a c ok, c b ok, b a ok. Distance2: 0-2: b c ok, 1-3: a b ok, 2-4: c a ok. So all good with 1 change. So answer 1.
DP should get 1.
Test 2: "abaac" length5: a b a a c. Adjacent: 0-1 a b ok; 1-2 b a ok; 2-3 a a not ok; 3-4 a c ok. Distance2: 0-2 a a? Actually positions0=a,2=a => equal, so palindrome "aba" is length3? Wait "aba" is palindrome length3 but also a palindrome of length3; indeed 0-2 equal => length3 palindrome. So need change. Changing third char (index2) from a to d? They said replace third character with d gives abdac: a b d a c. Check adj: a b ok, b d ok, d a ok, a c ok. Distance2: a d ok, b a ok, d c ok. So 1 change. DP should output 1.
Test 3: "codeforces". This likely already satisfies? Let's check: It's a random string. Need to ensure no adjacent equal and no distance2 equal. "codeforces" letters: c o d e f o r c e s? Actually spelling: c o d e f o r c e s. Check adjacent: c-o, o-d, d-e, e-f, f-o, o-r, r-c, c-e, e-s => all distinct? f-o distinct, o-r distinct, r-c distinct, c-e distinct, e-s distinct. So adjacent all distinct. Distance2: c-d? c and d distinct; o-e? o and e distinct; d-f? d and f distinct; e-o? e and o distinct; f-r? f and r distinct; o-c? o and c distinct; r-e? r and e distinct; c-s? c and s distinct. So all distinct. So 0 changes. DP outputs 0.
Test 4: "zeroorez". Let's check: z e r o o r e z. Adjacent: z-e ok, e-r ok, r-o ok, o-o not ok (adjacent equal). Also distance2: check: z-r? z != r; e-o? e != o; r-o? r != o? Actually positions 2=r,4=o? Wait careful: indices: 0:z,1:e,2:r,3:o,4:o,5:r,6:e,7:z. Adjacent: 3-4 o-o equal -> not ok. Also maybe distance2: 2-4: r vs o? distinct; 3-5: o vs r distinct; 4-6: o vs e distinct; etc. But also check palindrome? They say answer 1. So we can change one character. Maybe change the second o (index4) to something else, e.g., change to 'a' gives zeroorez? Actually "zeroarez"? But they claim 1. Let's try change index3 o to something: z e r a o r e z? That might break adjacency and distance2? Need to ensure no adjacent equal and no distance2 equal. Changing index3 from o to something not equal to r and not equal to e? Wait constraints: after change, check adjacency: 2-3: r-? must not equal; 3-4: ?-o must not equal; also distance2: 1-3: e-? must not equal; 2-4: r-o must not equal (but r!=o okay). So we can pick a letter distinct from r, o, e? Actually need ? != r (adjacent), ? != o (adjacent with next), and ? != e (distance2 with index1). So any letter not in {r,o,e} works, e.g., 'a'. So change one character yields valid. So answer 1.
DP should output 1.
Test 5: "abcdcba". This is palindrome itself. length 7. Need to avoid palindromes. They say answer 1. Let's see: a b c d c b a. Already has many palindromes. Need to change at least 1. They claim 1. Which change? Maybe change middle d to something? But then perhaps still have length3 palindromes? Let's test: If change position3 (d) to something else, say e, we get a b c e c b a. Check adjacent: a b, b c, c e, e c, c b, b a -> all distinct? c e distinct, e c distinct (e!=c), c b distinct, b a distinct, so adjacent ok. Distance2: a c? a!=c ok; b e? b!=e ok; c c? c and c at positions 2 and 4 become equal? positions: 2:c,4:c -> distance2 equal! That's a palindrome "cec"? Actually positions 2,3,4: c,e,c? That's a palindrome of length3 because c==c. So that's not allowed. So changing d to e introduces distance2 equal between positions2 and4? Actually originally they were c and c? Wait original indices: 0:a,1:b,2:c,3:d,4:c,5:b,6:a. So positions2=c,4=c originally equal, so there is a length3 palindrome "cdc"? Actually positions2,3,4: c,d,c is palindrome because c==c. So original already has palindrome length3. Changing d to something else still leaves c and c equal at distance2, so that palindrome persists unless we break one of the ends. So we need to change either position2 or position4 (or maybe other). Changing one of them to a different letter not equal to neighbors and not equal to the other? Let's try change position2 from c to something else, say x, while keeping rest: a b x d c b a. Need to check constraints: adjacent: a b, b x (b!=x ok), x d (x!=d), d c (d!=c), c b (c!=b), b a ok. Distance2: a x? a!=x ok; b d? b!=d ok; x c? x!=c need to ensure; d b? d!=b ok; c a? c!=a ok. So we need x != a? Actually distance2 from index0 to2? a and x must differ (a!=x). Also from index2 to4: x and c must differ (x!=c). Also from index1 to3: b and d must differ (b!=d). So we can pick x = something not equal to b (adjacent to index1), not equal to d (adjacent), not equal to a (distance2), not equal to c (distance2). Since alphabet 26, pick e.g., 'e'. That would work, change 1 character. So answer 1. So DP yields 1.
Test 6: "bbbbbbb" length7 all b's. Answer 4. Let's reason: We need a string of length7 with no two positions distance1 or2 equal. So essentially it must be a sequence where every three consecutive are distinct. This is like a 3-coloring problem. With alphabet 26, we can assign letters to each position such that they differ from previous two. The minimal number of changes from all b's to such a string: we need to choose assignments for each position (0..6) minimizing Hamming distance to "bbbbb...". This is a classic: we can treat it as we want to find a pattern that repeats with period something? Since constraint local, we can think of a string that avoids using 'b' at many positions. But DP will compute optimum.
Let's compute manually: For length7, what's minimal changes? Possibly we can keep some b's but need to ensure that any two adjacent are different, and any two with distance2 are different. So if we keep a b at a position, then its neighbors (i-1,i+1) cannot be b, and also the positions i-2,i+2 cannot be b? Actually distance2: if we have b at i, then positions i-2 and i+2 must not be b. So if we keep b at even indices, then odd indices cannot be b because adjacent, also indices i+2 cannot be b, which would be even indices again? Let's see: if we set pattern: positions 0,2,4,6 could be b? But adjacent positions: 0 and1 must differ, so 1 cannot be b; 2 and3 differ so 3 cannot be b; 4 and5 differ so5 cannot be b. That's fine. But distance2: positions 0 and2 both b? That's distance2, which is not allowed. So we cannot have two b's at distance2. So b can appear at most every third position? Actually constraint: if two positions have distance 2, they cannot be same. So if we have b at position i, then position i+2 must not be b. So b cannot be at both i and i+2. So the maximum set of positions that can be b without violating constraints (if we only care about b, but other positions can be other letters) is an independent set in a graph where edges between i and i+1 (adjacent) and i and i+2 (distance2). This graph is like a path with extra edges. The maximum independent set maybe floor((n+2)/3)? Let's compute: For a path with constraints that you cannot have two b's within distance <=2? Actually exactly: cannot have same letter at positions that are distance 1 or 2. So if we want to preserve original 'b's as many as possible, we need to select a subset of positions such that no two are adjacent and no two have distance exactly 2. This is equivalent to choosing positions with at least two indices gap? Because distance 2 means i and i+2 cannot both be chosen. So we need at least gap of 2? Actually if we choose i, we cannot choose i+1 (adjacent) and i+2 (distance2). So the next possible index is i+3. So we can choose i, i+3, i+6, ... So spacing at least 3. So maximum number of positions we can keep as b is ceil(n/3)? Let's see: for n=7, positions we can keep: if we start at 0, then 3,6 -> indices 0,3,6 (0 and3 distance3, 3 and6 distance3, 0 and6 distance6). That's 3 positions. But also we need to ensure that other positions don't conflict: e.g., if we keep b at 0,3,6, check adjacency: 0-1: b at0 and whatever at1, but if we keep b at0, position1 cannot be b (adjacent) but can be something else, that's fine. But check distance2: 0 and2 must not both be b; we didn't keep 2, so ok. 3 and5: 5 not b, ok. 1 and3: distance2? 1 and3 distance2, but 1 is not b, so fine. So 3 b's possible. But is it always achievable with other letters? Yes, we can assign other positions any letters that satisfy constraints and not b. So maximum number of b's we can retain is floor((n+2)/3)? Actually for n=7, maximum independent set with min distance 3 yields ceil(n/3) maybe? Let's compute: with spacing 3, pattern 0,3,6 gives 3, and 7/3≈2.33, ceil gives 3. Also starting at 1: 1,4 gives 2. Starting at 2: 2,5 gives 2. So maximum is 3. So we can keep at most 3 b's, so changes at least 7-3=4. So answer 4 matches. So DP should give 4.
Test 7: "a" -> 0.
Thus DP matches sample.
Now let's consider other tests: "aa" length2, expected 1. "ab" length2 expected 0. "aba" length3: check original: a b a. Adjacent: a!=b ok, b!=a ok. Distance2: a and a equal -> not ok. So need to change at least 1. Could change middle b to something else? But then a ? a: distance2 a and a still equal. So need to change one of the ends. Change first a to c: c b a: adjacent c!=b ok, b!=a ok; distance2 c and a distinct -> ok. So 1 change. Also maybe change both? Minimum 1. So answer 1. DP would compute.
Now consider "abc" length3: a b c. Adjacent all distinct, distance2 a and c distinct. So 0.
Now consider "abca" length4: a b c a. Adjacent: a b, b c, c a all distinct. Distance2: a c? a!=c ok; b a? b!=a ok. So 0? But check palindrome substrings: "aba"? No because positions 0,1,2 are a,b,c not palindrome. "bcb"? not. "abc a"? maybe "a...a"? But substring "aa"? not present. So seems fine. However, does it contain a palindrome of length 3? Check positions 1,2,3: b,c,a -> not palindrome. So 0 changes. But is there any palindrome of length 2? none. So 0. So DP would give 0.
Now consider "abac" length4: a b a c. Adjacent: a b, b a, a c all distinct. Distance2: a a? positions0 and2 both a -> equal, so palindrome "aba" length3. So need change. So answer 1.
Now complexity: total sum n up to 1e5, DP O(n*26^2) ~ 6.76e7 operations. In C++ should be fine within 1-2 seconds. But we need to be careful with constant factors: loops over 26, using arrays, INF large, etc. Also we have t up to 1e5, but total n sum bounded, so many small strings. For each test case we allocate and run DP. For very short strings (n=1,2), we can handle quickly with early returns to avoid heavy loops.
But note: For n=2, we still do initialization of dp with 2626 (676) and then take min. That's fine and total for many small strings may add up to sum of n? Actually sum of n is 1e5, so total number of characters is 1e5. But for each test case with length 2, we do ~676 operations. If there are many test cases of length 1 or 2, total operations may be up to t * 676, where t can be up to 1e5 but sum n = 1e5, so if all test cases are length 1, t=1e5, each does O(1) for length1 (we skip DP) -> fine. For length 2, if all test cases length 2, then number of test cases = 5e4 (since sum n=1e5). Each does ~676 operations -> total 5e4676 = 33.8 million, still okay. For length 3, each does DP for n=3: init (676) + one iteration of i=2 (maybe ~676) = 1352, total 3.33e4 test cases? Actually if all length 3, number of test cases ~33334, total ops ~33334*1352 = 45 million. So still within range. So overall fine.
But we can micro-opt: For n>=2, we could do DP with size 26x26 but we can restrict states to only those characters that appear? Not necessary.
We must ensure to use integer arrays with fixed size, avoid vector overhead per test case. Use std::array<std::array<int,26>,26> maybe.
Also, note that INF should be something like n+5, since max changes <= n. So set INF = 1e9 or n+10.
Implementation plan:
-
Read t.
-
For each test case:
-
Read string s.
-
n = s.size()
-
if n == 1: print 0; continue;
-
Convert s to vector a of length n, with a[i] = s[i]-'a'.
-
Declare dp as 26x26 array of ints, set all to INF.
-
For i in 0..25:
for j in 0..25:
if i != j:
dp[i][j] = (i != a[0]) + (j != a[1]);
-
For idx = 2; idx < n; idx++:
int cur = a[idx];
// compute mins
int min1[26], min2[26], minChar[26];
for (int b=0; b<26; ++b) {
int m1 = INF, m2 = INF, c1 = -1;
for (int a_=0; a_<26; ++a_) {
if (a_ == b) continue;
int v = dp[a_][b];
if (v < m1) {
m2 = m1; m1 = v; c1 = a_;
} else if (v < m2) {
m2 = v;
}
}
min1[b] = m1;
min2[b] = m2;
minChar[b] = c1;
}
// new dp
array<array<int,26>,26> ndp;
for (int b=0; b<26; ++b) {
for (int c=0; c<26; ++c) {
ndp[b][c] = INF;
}
}
for (int b=0; b<26; ++b) {
int m1 = min1[b];
int m2 = min2[b];
int forbidChar = minChar[b];
for (int c=0; c<26; ++c) {
if (b == c) continue;
int best = (forbidChar != c) ? m1 : m2;
// Edge: If m1 is INF? But that shouldn't happen because there is at least one valid a. For b, there are 25 a's, so at least one valid dp entry must be finite? Actually initially dp entries for some states may be INF if unreachable? But after first initialization, dp contains entries for all a,b with a!=b, each finite (cost <=2). So all m1 finite. In later steps, also finite because we always can extend? Possibly if we get a state where dp[a][b] = INF for all a? That would mean no valid string up to i with that last two chars. But because alphabet size 26 >=3, there will always be at least one valid extension for each previous state? However, it might be that some states become INF if they are impossible to achieve? But still for each b there should be at least one a such that dp[a][b] finite? Not necessarily: Suppose we have a string that leads to a certain pair (a,b) but if we cannot reach that pair due to constraints? But we start with all pairs possible (by changing characters). So all pairs have finite cost initially (since we can set any letters for first two at some cost). Then when we extend, for each b, there will always be some a with finite cost because from previous dp all a,b pairs are finite? Wait, after first iteration (i=2), we compute ndp[b][c] as best + cost. For a given b, there is at least one a (since a != b) with finite dp[a][b] (since all dp[a][b] from initialization are finite). So m1 finite. Therefore ndp[b][c] will be finite for some c. So all subsequent steps, dp entries may become INF if they are unreachable? But can a pair (b,c) become unreachable? For given b,c, we need existence of some a with a!=b, a!=c. Since alphabet 26, there are many a's, and if all such a's led to INF in previous dp? But previous dp for pairs (a,b) might have some finite. However, it's possible that for a fixed b, all a that satisfy a!=b might have dp[a][b] = INF? That would mean that there is no way to have a valid prefix ending with ... a,b. But is that possible? Since we can always construct some string, there should be at least one pair (a,b) with finite cost. So for each b, there will be at least one a with finite dp[a][b]? Not guaranteed: suppose for a particular b, maybe all a that are not equal to b have dp[a][b] = INF because those states are impossible? But can they be impossible? Let's think: The constraints are only about the last two characters? For a prefix of length i+1 (positions 0..i), the state (a,b) means s[i-1]=a, s[i]=b. The prefix must satisfy all constraints internally. Could it be that no valid prefix ends with a particular (a,b)? Possibly, if a==b, then invalid, but we exclude those. For a!=b, there could be a valid prefix. But is it always possible to construct a prefix ending with any given (a,b)? Not necessarily; because the earlier characters must satisfy constraints with a and b. For example, length 2: any pair (a,b) with a!=b is valid (since no further constraints). So all 650 pairs are valid and have finite cost (changing accordingly). So initial dp has all a!=b finite. Then when extending to length 3, for a given b,c (b!=c), we need a such that a!=b and a!=c. Since there are 24 such a's (since a can't be b or c), and at least one of those a's had finite dp[a][b] from previous step. Since all dp[a][b] were finite, at least one of those a's will be allowed (a != c), thus best is finite. So ndp[b][c] will be finite for all b!=c? But note: cost for choosing c may be high, but still finite. So after extension, all ndp[b][c] for b!=c are finite? Possibly yes, because for each b,c, we can take some a (e.g., the a that gave min for that b but if that a equals c, we can take second min which is also finite). Since all dp[a][b] are finite, min1 and min2 are finite. Thus ndp[b][c] finite for all b!=c. So indeed after each step, dp remains finite for all a!=b. So we can assume min1, min2 finite.
Thus implementation safe.
Now answer at end: min over dp[a][b].
But note: For n=2, we haven't computed any extensions; dp is as initialized. So answer = min_{a!=b} dp[a][b]. That's correct.
Now we can code.
But need to be careful with integer overflow: INF set to something like 1e9.
Now let's consider if there is any simpler solution. Possibly we can think of dynamic programming on positions with only 3 states representing the actual character? But alphabet size 26, so DP with 26 states per position (like dp[i][c] = min changes to make prefix up to i valid and ending with character c, but also need to know the previous character to enforce distance2). That's similar to dp[i][c1][c2] but we compressed to two letters.
Alternate approach: Since constraints only disallow equality at distance 1 and 2, we can think of it as a graph coloring with 3 colors? Actually we have 26 colors, so we can always assign a valid character distinct from previous two. So the main difficulty is to minimize changes. This is essentially a problem of "minimum cost to make a string have no repeats within distance 2". This is similar to problems like "make string have no two adjacent equal" (minimum changes) which is easy: just change each run optimally? For distance 2 constraint, it's more complex.
But maybe we can treat it as a shortest path on a de Bruijn graph? That's what we did.
Given constraints, DP should pass.
Now double-check the equivalence: Is there any palindrome of length 2 or 3 that is not contiguous? The definition says substring, which is contiguous. So we are correct.
Now consider a palindrome of length 2: "aa". That's covered.
Palindromes of length 3: "aba", "bbb", etc. That's covered.
Thus good.
Now potential pitfalls: The problem statement said "substring" is defined as deleting characters from the beginning and end, which indeed yields a contiguous substring. So okay.
Now edge case: empty string? Not given; strings non-empty.
Now check if any other palindromes could appear without containing length-2 or length-3 palindrome? For length 4, it contains a length-2 palindrome (the middle two) as we argued. For length 5, contains length-3 palindrome. For length 6, contains length-2 palindrome? Actually "abc cba" includes "cc"? Wait "abccba" has "cc" length2. But what about "abcxyzcba"? That's length 9, but it's not contiguous? Actually substring must be contiguous. For palindrome "abc d cba"? That's length 7? The middle three? More generally, any palindrome length L >=4: if L even, the two middle characters are at positions (i+L/2-1) and (i+L/2) are symmetric and equal, thus a length-2 palindrome. If L odd, the three middle characters (positions i+(L-1)/2 -1, i+(L-1)/2, i+(L-1)/2+1) form a palindrome of length 3. So indeed any palindrome of length >=4 contains a palindrome of length 2 or 3 as a contiguous substring. So equivalence holds.
Thus DP solution is correct.
Now implementation details:
We can store dp as int dp[26][26] and use nested loops. Since we will be resetting for each test case, we can just declare and fill with INF.
For the mins computation, we can use arrays of size 26.
Potential micro-optimizations: Use static arrays to avoid repeated allocation. But within each test case, we can allocate on stack (automatic arrays) since 26 is small.
Better to use int dp[26][26] and int ndp[26][26] as local variables.
But careful: In the loops, we need to set ndp to INF each iteration. Since 26*26=676, it's fine.
Now I'll code in C++.
Now consider very long strings: n up to 1e5. Loop per character: for each i, we do about 2626 operations for mins (2626 for scanning all a for each b) = 676, plus 26*25 for updating ndp = 650, total ~1326 per char. That's about 132.6 million for 1e5, which might be a bit high but still okay? Wait 1326 per char * 100,000 = 132,600,000, about 1.3e8 operations. That's more than previous estimate (I earlier estimated 676 per char). Let's recalc:
-
For mins: for each b (26) we loop over a (26) => 26*26 = 676 operations. Inside we do comparisons, assignments. So 676.
-
For ndp: for each b (26) we loop over c (26) but skip when b==c, so about 26*25 = 650 operations. So total ~1326 per character.
That's 132.6 million for n=1e5. This is still acceptable in C++ if optimized (no heavy operations). 1.3e8 simple integer operations can run within 1-2 seconds on modern CPUs, especially with compiler optimizations. However, we need to be cautious about constant factors: loops, array accesses. But should be okay.
But we can reduce the work: Actually we can combine the mins and ndp more efficiently? Perhaps we can compute for each b the best values for each c directly without scanning all c? But we already need to compute ndp for all (b,c) pairs. That's 650 entries, which is necessary to fill the new dp. However, we could compute mins for each b and then fill ndp by iterating over c, which we do. So cannot reduce below 650 per char for ndp. But maybe we can avoid scanning all a for each b each time by using a precomputed structure? But 676 per char is small.
Total operations: For n=1e5, 1326 * 1e5 = 132.6e6 ≈ 1.33e8. This is borderline but likely okay given that sum of n is 1e5. But note that we also have initialization: 676 operations for n>=2, and final min: 676. So overall about 1.33e8. In practice, with C++ and -O2, it should be fine. Typical guideline: 1e8 operations in 1 second maybe borderline but often passes on Codeforces if constant small. This is just integer comparisons and assignments, no heavy data structures. So okay.
But we can try to reduce constant: Instead of computing mins for each b by scanning all a each time, we could maintain for each b the min and second min from previous dp and update? But dp changes each iteration; we would need to recompute from scratch anyway. Since dp is small, recompute is fine.
Alternatively, we could use DP with only 3 states: we could treat it as a graph where each state is the last character and the character before last, but we can use bitmask? Not helpful.
I think it's fine.
But note: t up to 1e5, but sum n is 1e5, so many test cases will have small n. For small n, overhead per test case (like initialization of dp with INF) could be large if we do 676 assignments each time. But still total assignments across all test cases is at most 676 * number_of_testcases_with_n>=2. Since total n sum 1e5, number of test cases could be as many as 1e5 (if each n=1). For n=1 we skip dp. For n=2, we do initialization 676, and final min 676, but no loop. So worst-case scenario: 5e4 test cases with n=2, each doing ~1352 operations -> 67.6 million, plus 5e4*? Actually 5e4*1352 = 67.6 million. That's also fine. So total operations perhaps up to 200 million, still okay.
Thus proceed.
Now we should confirm that DP works for all cases.
Let's test a few more.
Case: n=2, s="aa". dp init: for a,b with a!=b: cost = (a != 0?)+ (b !=0?). For a=0,b=1: cost = (0!=0?0)+(1!=0?1) =1. Similarly other pairs. Minimal cost is 1 (e.g., a=0,b=1 or a=1,b=0 etc). So answer 1.
Case: n=2, s="ab": s[0]=0, s[1]=1. dp[0][1] cost=0+0=0, so answer 0.
Case: n=3, s="aba": a=0,1,0. dp init for positions 0,1: all pairs (a,b) with a!=b. Then idx=2 (original 0). Compute mins and ndp.
We can manually compute minimal changes should be 1.
Let's simulate quickly:
Initial dp[ a0 ][ b1 ] = cost for first two chars being (a0,b1). cost = (a0 != 0?0? ) + (b1 != 1?). But careful: s[0]=0, s[1]=1.
So dp[0][1] = 0+0=0.
dp[0][2] = (0!=0?0)+(2!=1?1)=1.
... many others.
Now we need to compute ndp for position2. The answer should be min over (b,c) at end.
We can compute quickly but trust.
Now also consider that we might be able to change more than one character, but DP picks min.
Now confirm for "bbbbbbb" we get 4.
Now is there any nuance about the possibility of having a palindrome substring of length exactly 1? Not considered, so fine.
Now I'll implement.
But note: In the DP, we treat the cost for each character change as 1. We don't need to differentiate.
Now one more consideration: Since we can change any character arbitrarily, and we are allowed to replace with any lowercase letter, we have 26 options.
But what if alphabet were only 2 letters? Then constraint might be impossible for some lengths? But with 26, it's always possible: we can construct a string with no two within distance 2 equal by using three distinct letters in rotation, e.g., "abcabc...". So always feasible.
Thus DP will always find a finite answer.
Now I'll produce code.
Implementation steps:
-
include bits/stdc++.h using namespace std.
-
const int INF = 1e9; or maybe 1e6.
-
function solve():
int t; cin >> t;
while(t--){
string s; cin >> s;
int n = s.size();
if(n == 1){
cout << "0\n";
continue;
}
vector a(n);
for(int i=0;i<n;++i) a[i] = s[i]-'a';
int dp[26][26];
// initialize to INF
for(int i=0;i<26;++i) for(int j=0;j<26;++j) dp[i][j]=INF;
// base: positions 0 and 1
for(int i=0;i<26;++i){
for(int j=0;j<26;++j){
if(i==j) continue;
int cost = (i != a[0]) + (j != a[1]);
dp[i][j] = cost;
}
}
// iterate for positions 2..n-1
for(int idx=2; idx < n; ++idx){
int cur = a[idx];
// precompute min1,min2,minChar for each b
int min1[26], min2[26], minChar[26];
for(int b=0;b<26;++b){
int m1 = INF, m2 = INF, c1 = -1;
for(int a_=0;a_<26;++a_){
if(a_ == b) continue;
int v = dp[a_][b];
if(v < m1){
m2 = m1;
m1 = v;
c1 = a_;
}else if(v < m2){
m2 = v;
}
}
min1[b] = m1;
min2[b] = m2;
minChar[b] = c1;
}
// new dp
int ndp[26][26];
for(int i=0;i<26;++i) for(int j=0;j<26;++j) ndp[i][j] = INF;
for(int b=0;b<26;++b){
int m1 = min1[b];
int m2 = min2[b];
int forbid = minChar[b];
for(int c=0;c<26;++c){
if(b == c) continue;
int best = (forbid != c) ? m1 : m2;
// best should be finite, but just in case check
if(best >= INF) continue; // not needed
int cost = (c != cur) ? 1 : 0;
ndp[b][c] = best + cost;
}
}
// copy ndp to dp
for(int i=0;i<26;++i) for(int j=0;j<26;++j) dp[i][j] = ndp[i][j];
}
int ans = INF;
for(int i=0;i<26;++i){
for(int j=0;j<26;++j){
if(i==j) continue;
if(dp[i][j] < ans) ans = dp[i][j];
}
}
cout << ans << "\n";
}
That should work.
Now test with sample. We can run mental for small.
But we must check the indexing: For n=2, we skip loop, then ans computed from base dp. Good.
Now consider performance: copying dp 26x26 each iteration (or we could use swap pointers). But copying 676 ints per iteration is cheap. However, we could use two arrays and swap pointers to avoid copying. But copying is fine; 1e5 * 676 = 67.6 million assignments, which is okay. But we already have 1326 per char, adding 676 copying = 2002 per char, still okay. Actually we already have ndp initialization (set to INF) which is 676 assignments, then we fill ndp with values for valid pairs (maybe 650 assignments), then we copy back 676 assignments. So total assignments maybe 676 (init) + 650 (fill) + 676 (copy) = about 2002. So per char about 2000 operations. 2000 * 1e5 = 200 million assignments, still okay. But we can reduce by using two arrays and swapping pointers without resetting entire ndp to INF? Actually we need to reset ndp for each b,c combination to INF because we only set those with b!=c. But if we reuse same ndp array, we need to reset only the entries we will use? But we set all b,c with b!=c to computed values; we can set them directly without resetting, but then the entries for b==c would remain from previous iteration and could be mistakenly considered as valid if we later use them? But we never use b==c states because we only consider those where b!=c when copying to dp? Actually after computing ndp, we copy it entirely to dp. But dp should have INF for b==c because those states are invalid. So we must ensure ndp[b][c] = INF for b==c. So we need to set those to INF. That's 26 entries (since b==c only 26). But we also need to set for b!=c that we didn't set? We set all b!=c in the loop; so we don't need to reset them. So we can first set ndp[b][b] = INF for all b (26 assignments). Then for each b, for each c!=b, compute and assign ndp[b][c]. That avoids resetting all 676 entries. Then we can swap pointers. But we still need to ensure that for b!=c entries that we don't assign? Actually we assign all b!=c because we loop over all b and c where b!=c. So all pairs are covered either by INF for b==c or assigned. So we don't need to initialize the whole array to INF; just set the diagonal to INF. However, we also need to ensure that ndp is cleared from previous values for b!=c that we didn't assign? But we assign all b!=c, so no leftover. So we can avoid the 676 initialization. That reduces per iteration 676 assignments. Similarly, we can avoid copying back by using two pointers and swapping. So we can maintain dp1 and dp2, and after each iteration, swap references.
Let's adopt optimization to be safe.
Implementation:
int dp[26][26];
int ndp[26][26];
// Initialize dp with INF
...
for idx in 2..n-1:
// compute mins from dp
// compute ndp: first set diagonal to INF
for (int i=0;i<26;++i) ndp[i][i] = INF;
// for each b, for each c != b, compute and assign ndp[b][c]
...
// swap pointers: std::swap(dp, ndp);
// or manually copy? We'll just swap.
But careful: dp and ndp are arrays, swapping entire arrays might be heavy but we can swap pointers if we use pointers to arrays? Actually we can't swap arrays easily; we can use two 2D arrays and after computing ndp, we can copy back using memcpy or just assign dp = ndp? Not possible with raw arrays. We could use vector of vectors, but that might be slower. Alternatively, we can keep dp as array and at the end of each iteration, we can copy ndp into dp. But copying 676 ints is not heavy. However, to reduce, we could use std::array<std::array<int,26>,26> which supports assignment (copy) which is fine. But assignment of 676 ints is still copying. But that's okay.
Simplify: Use std::array<std::array<int,26>,26> for dp and ndp. Then at the end: dp = ndp; That will copy 676 ints.
That's fine.
But we can also just keep dp as vector<vector>(26, vector(26, INF)), but same.
I'll use int dp[26][26] and int ndp[26][26] and after loop, copy using nested loops (26*26). It's simple.
But to reduce assignments: I'll initialize ndp with INF only for diagonal? Actually to be safe, I'll set entire ndp to INF at start of each iteration, but that's 676 assignments. I think it's fine.
Given total operations 200 million, which is okay, I'll keep it simple.
But note: In the innermost loops, we are doing a lot of branching. Could we simplify the condition (forbid != c) ? m1 : m2? That's fine.
Now test with sample.
But before finalizing, I'll run a mental small test: n=2, s="ab". Our dp init: we set dp for all i!=j. dp[0][1] = 0. Then ans = min = 0. Good.
Test n=2, s="aa": dp[0][1] = (0!=0?0)+(1!=0?1)=1, dp[1][0]=1, dp[0][2]= (0!=0?0)+(2!=0?1)=1, many have cost 1. Some have cost 2 if both mismatched, but min is 1. So answer 1.
Test n=3, s="aaa". Expect? Original: a a a. Must have no adjacent equal: so need to change at least two? Actually we need all three distinct? Check constraints: adjacent: positions 0-1 must differ, 1-2 must differ, distance2: 0-2 must differ. So all three must be distinct. With alphabet 26, we can change two characters to achieve three distinct letters. But can we do with one change? Suppose change middle to b: a b a. Then adjacent: a b ok, b a ok. Distance2: a a not ok (since 0 and2 both a). So need to change one of the ends as well. If change position0 to b: b a a -> adjacent b a ok, a a not ok (adjacent). So need to change position2 as well? Actually b a c? Let's try change position2 only: a a c -> adjacent a a not ok. Change position0 only: b a a -> adjacent a a not ok. So need at least two changes? Could we change position0 and position1? b c a: b c ok, c a ok, distance2 b a ok? b and a distinct. So 2 changes. Change position1 and position2: a b c: a b ok, b c ok, distance2 a c ok. So 2 changes. Change all three? Not needed. So minimal changes = 2. Let's see if DP yields 2.
Our DP for "aaa" (a=0,0,0).
Initialize dp for positions 0,1: For all i!=j, dp[i][j] = (i!=0)+(j!=0). The minimum among these is when one of them matches 0 and the other doesn't: cost=1 (e.g., i=0,j=1 => 0+1=1; i=1,j=0=>1+0=1). So min dp =1 for some states.
Then idx=2 (third char, original 0). Compute mins for each b. Then compute ndp.
We want to see minimal final ans.
Let's compute manually: For b=0, we need to compute min1,min2 for b=0 from dp[a][0] for a!=0. dp[a][0] values: For a=0? not allowed (a!=0). So a from 1..25. For each a, dp[a][0] = (a!=0)+(0!=0)= (a!=0?1:0)+0 = 1 for all a!=0? Actually (a!=0) is 1 if a !=0, which is always true since a from 1..25, so cost=1. So for b=0, all dp[a][0]=1. So min1[0]=1, min2[0]=1 (since all equal), minChar[0] = some a, say 1.
Now for b != 0, consider b=1. dp[a][1] for a!=1. For a=0: dp[0][1] = (0!=0)+(1!=0)=0+1=1. For a=2: dp[2][1] = (2!=0)+(1!=0)=1+1=2? Actually (2!=0) is 1 because 2!=0, plus (1!=0) is 1 =>2. So not all equal. The minimum for b=1 is probably 1 (from a=0). So min1[1]=1, min2[1] maybe also 1? Actually there might be only one a giving 1? Let's check a=0 gives 1; other a maybe? a= something else that also matches original? original first two are 0,0. dp[a][1] = (a!=0)+(1!=0) = (a!=0)+1. To be 1, we need (a!=0)=0 => a=0, but a=0 not allowed because a!=b? b=1, so a=0 is allowed (since a!=b). So only a=0 yields 0+1=1. Others yield at least 2. So min1[1]=1, min2[1]=2.
Now for b=0, we will compute ndp[0][c] for c != 0. For c=1: best = (minChar[0]!=1)? min1[0] : min2[0]. minChar[0] is some a, say 1, which equals c=1? So best = min2[0]=1. cost = (c != cur)? cur=0, c=1 -> cost=1. So ndp[0][1] = 1+1=2. For c=2: minChar[0] maybe 1, not equal 2 => best=min1[0]=1, cost=1 (since 2!=0) => 2. So ndp[0][c] for all c!=0 yields 2? Actually best always 1, cost always 1 (since c !=0) so ndp[0][c]=2.
Now for b=1, c !=1. For c=0: best = (minChar[1]!=0)? min1[1] : min2[1]. minChar[1] probably =0 (since a=0 gave min). So minChar[1]=0, c=0 => equal, so best = min2[1]=2. cost = (c != cur)? cur=0, c=0 -> cost=0. So ndp[1][0] = 2+0=2. For c=2: minChar[1]=0 !=2 => best=min1[1]=1, cost=1 => 2. So ndp[1][2]=2.
For b=2, etc. Many ndp values will be 2. Also possibly some ndp might be 3? But minimum among all ndp appears to be 2. So ans = 2. Good.
Thus DP works.
Now for "bbbbbbb" length 7, we expect answer 4. Let's check if DP would yield 4. Likely.
Now consider "abcabcabc"... This string already satisfies? Let's check: a b c a b c a b c. Adjacent: a b distinct, b c distinct, c a distinct, a b distinct, etc. All good. Distance2: a c? a and c distinct; b a distinct; c b distinct; a c? okay. So 0 changes. DP would output 0.
Now all good.
Now we must ensure we read input correctly; t up to 1e5, sum length 1e5, so using cin with string may be fine but could be slow. We can use ios_base::sync_with_stdio(false); cin.tie(NULL); to speed up.
Now I'll produce final solution.
But before final, I should double-check the DP transition for correctness in handling the case when n=2: we take min over all dp entries with a!=b. That's fine.
Now for n=0? Not.
Now also consider that we could have a scenario where after processing, some dp entries may be INF because they are impossible? But as argued, they will be finite. But just in case, we take min only over finite ones, and INF will be large.
Now the answer is at most n, and we initialize INF as n+5 or 1e9.
Now let's code.
But I should also think about alternative simpler greedy or DP with only 3 states? Could we treat the string as three positions mod something? Since constraint is local, maybe we can color the string with a pattern of period 3 using 3 letters, but we want to minimize changes, so it's like we want to assign each position one of 26 letters, but we can choose any. This is similar to "minimum cost to make string a proper coloring of a path graph with distance-2 constraints". That can be solved by DP with 26 states per position (previous char) and also track the char before previous? That's essentially 26^2 states.
Could we reduce to 26*3? Not easily.
Thus DP is appropriate.
Now final note: In the problem statement, substring is defined as deleting from beginning and end, so it's contiguous. Good.
Now I'll write final solution.
Implementation details:
-
Use int for everything.
-
Use INF = 1e9.
-
For each test case, if n==1: print 0, continue.
-
Convert string to vector maybe or just use s[i] - 'a' in loops, but we need to access original at each index. We can keep string s and convert on the fly. But in loops, we need a[idx] multiple times, so better to convert once.
Now final code.
But before finishing, let's test with some custom cases.
Case: t=1, s="ab". Expect 0. Our code: n=2 >1, init dp. Then ans = min dp. Should be 0.
Case: s="aaabbb". length6. Let's compute manually? Possibly answer? We'll trust DP.
Now check for n=3 "aba". We already did mentally should be 1. Let's compute with DP quickly.
Initial dp: s[0]=0, s[1]=1.
dp[0][1] = 0; dp[0][2]=1; dp[1][0]=1; dp[1][2] = (1!=0?1)+(2!=1?1)=2; dp[2][0]= (2!=0?1)+(0!=1?1)=2? Actually (2!=0) is 1, (0!=1) is 1 =>2; dp[2][1]= (2!=0?1)+(1!=1?0)=1; etc.
Now idx=2 (cur=0). Compute mins:
For b=0: dp[a][0] for a!=0. Check a=1: dp[1][0]=1; a=2: dp[2][0]=2; others >? Actually a from 3..25: dp[3][0] = (3!=0?1)+(0!=1?1)=2? Actually (3!=0) is 1, (0!=1) is 1, so 2. So min1[0]=1 (a=1), min2[0]=2 (a=2). minChar[0]=1.
For b=1: dp[a][1] for a!=1. a=0: dp[0][1]=0; a=2: dp[2][1]=1; a=3: dp[3][1] = (3!=0?1)+(1!=1?0)=1? Actually (3!=0) 1, (1!=1) 0 ->1; so min1[1]=0 (a=0), min2[1]=1 (a=2 or 3). minChar[1]=0.
For b=2: dp[a][2] for a!=2. a=0: dp[0][2]=1; a=1: dp[1][2]=2; others: 2. So min1[2]=1 (a=0), min2[2]=2 (a=1). minChar[2]=0.
Now compute ndp:
We'll compute candidate ndp entries that could lead to minimal answer.
Consider b=1, c=0: b=1, c=0 (c!=b). best: minChar[1]=0 equals c => use min2[1]=1. cost = (c != cur? cur=0, c=0 =>0). So ndp[1][0] = 1.
Consider b=0, c=1: best: minChar[0]=1 equals c => use min2[0]=2, cost = (c!=0?1) => 3. So ndp[0][1]=3.
Consider b=2, c=0: best: minChar[2]=0 equals c => min2[2]=2, cost = (0!=0?0) =>2 -> ndp[2][0]=2.
Consider b=0, c=2: best: minChar[0]=1 !=2 => min1[0]=1, cost=(2!=0?1) =>2.
Consider b=1, c=2: best: minChar[1]=0 !=2 => min1[1]=0, cost=(2!=0?1) =>1. So ndp[1][2]=1.
Consider b=2, c=1: best: minChar[2]=0 !=1 => min1[2]=1, cost=(1!=0?1) =>2. So ndp[2][1]=2.
Consider b=0,c=... all yield >=2.
Consider b=1,c=... we have ndp[1][0]=1, ndp[1][2]=1.
Consider b=2,c=... we have ndp[2][0]=2, ndp[2][1]=2, etc.
Thus minimal ndp value = 1. So ans = 1. Good.
Thus DP works.
Now confirm for "bbbbbbb" length7. Let's try to estimate quickly: we can keep at most 3 b's, so answer 4. DP should give 4.
Now one more edge: n=2 with s="ab" we get 0.
Now final code.
Potential improvements: Use char - 'a' directly in loops, store as int.
Now incorporate everything.
Now produce final answer.
But wait: There's nuance: The condition we derived (no palindrome length 2 or 3) is necessary and sufficient. However, is there any scenario where a palindrome length >3 doesn't contain a palindrome length 2 or 3? Let's double-check thoroughly:
Consider palindrome of length 4: s[i] = s[i+3], s[i+1] = s[i+2]. The substring s[i+1..i+2] is length 2 and its two characters are equal, so it's a palindrome of length 2. So yes.
Consider palindrome of length 5: s[i] = s[i+4], s[i+1] = s[i+3]. The substring s[i+1..i+3] is length 3, and because s[i+1]=s[i+3] and middle s[i+2] is any, that substring is a palindrome of length 3. So yes.
Consider palindrome of length 6: s[i] = s[i+5], s[i+1] = s[i+4], s[i+2] = s[i+3]. The substring s[i+2..i+3] is length 2, and s[i+2] = s[i+3] because they are equal from palindrome condition? Actually from s[i+2]=s[i+3]? Wait condition for length 6: indices: i, i+1, i+2, i+3, i+4, i+5. Palindrome condition: s[i] = s[i+5], s[i+1] = s[i+4], s[i+2] = s[i+3]. So indeed s[i+2] = s[i+3], so the middle two are equal, forming a length-2 palindrome. So yes.
Thus any palindrome length >=4 always contains a palindrome of length 2 (if even) or 3 (if odd). So equivalence stands.
Thus DP is correct.
Now, is there any need to consider overlapping palindromes? No, DP covers all.
Thus final answer.
Now I will produce final C++ solution.
I'll also include comments.
Testing: Given sample input, we should get sample output.
Now implement.
I'll code as:
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while(t--) {
string s;
cin >> s;
int n = s.size();
if(n == 1) {
cout << "0\n";
continue;
}
vector a(n);
for(int i=0; i<n; ++i) a[i] = s[i] - 'a';
int dp[26][26];
for(int i=0; i<26; ++i) for(int j=0; j<26; ++j) dp[i][j] = INF;
// initialize for first two positions
for(int i=0; i<26; ++i) {
for(int j=0; j<26; ++j) {
if(i == j) continue;
int cost = (i != a[0]) + (j != a[1]);
dp[i][j] = cost;
}
}
for(int idx=2; idx < n; ++idx) {
int cur = a[idx];
int min1[26], min2[26], minChar[26];
// compute for each b the best two previous a's
for(int b=0; b<26; ++b) {
int m1 = INF, m2 = INF, c1 = -1;
for(int a_=0; a_<26; ++a_) {
if(a_ == b) continue;
int v = dp[a_][b];
if(v < m1) {
m2 = m1;
m1 = v;
c1 = a_;
} else if(v < m2) {
m2 = v;
}
}
min1[b] = m1;
min2[b] = m2;
minChar[b] = c1;
}
int ndp[26][26];
// initialize ndp with INF (we will set all b,c with b!=c)
for(int i=0; i<26; ++i) for(int j=0; j<26; ++j) ndp[i][j] = INF;
for(int b=0; b<26; ++b) {
int m1 = min1[b];
int m2 = min2[b];
int forbid = minChar[b];
for(int c=0; c<26; ++c) {
if(b == c) continue;
int best = (forbid != c) ? m1 : m2;
// best is finite
int cost = (c != cur) ? 1 : 0;
ndp[b][c] = best + cost;
}
}
// copy back
for(int i=0; i<26; ++i) for(int j=0; j<26; ++j) dp[i][j] = ndp[i][j];
}
int ans = INF;
for(int i=0; i<26; ++i) {
for(int j=0; j<26; ++j) {
if(i == j) continue;
ans = min(ans, dp[i][j]);
}
}
cout << ans << "\n";
}
return 0;
}
Now test with sample.
I'll quickly simulate with sample using mental run for codeforces: n=10? Actually "codeforces" length 10. Our DP should compute 0. Since it's already valid, initialization: first two letters 'c','o' (2,14?). Actually 'c'=2, 'o'=14? Let's not bother. The dp will have many states, but the state corresponding to actual letters will have cost 0. In transitions, the real sequence will have dp value 0 and propagate, so final ans 0.
Now "zeroorez": length 8. Should give 1.
Now "abcdcba": length 7, answer 1.
Now "bbbbbbb": length 7, answer 4.
Now "a": answer 0.
Now we need to ensure that for n=2, if the string already has no palindrome length 2 (i.e., s[0]!=s[1]), answer 0. Our dp min will include that state.
Now potential issue: For n=2, our dp initialization sets dp[i][j] for i!=j. If s[0]!=s[1], dp[s0][s1] = 0, so answer 0. Good.
Now, is there any case where dp could yield answer less than 0? No.
Now, what about very long strings? Should be fine.
Now finalize.
But wait: Are we sure that the condition "no palindrome substring of length >1" is exactly the condition that no two characters at distance 1 or 2 are equal? Let's double-check if there could be a palindrome of length 2 or 3 that does not involve adjacent or distance-2 equality? Actually length 2 palindrome requires two equal adjacent characters. Length 3 palindrome requires first and third equal (distance 2) regardless of middle. So yes.
Thus the DP ensures those conditions.
One more nuance: Could there be a palindrome of length 4 that does NOT contain a palindrome of length 2? Consider "abca"? That's not palindrome. For palindrome length 4, the condition is s[i]=s[i+3] and s[i+1]=s[i+2]. So the middle two are equal, so there is a palindrome of length 2. So it's impossible to have a length 4 palindrome without a length 2 palindrome. So correct.
Now, what about palindrome of length 1? Ignored.
Thus solution stands.
Now, note that the problem might be originally from Codeforces Round, and I recall a problem "Orpheus' poem" or something. Actually I think there is a Codeforces problem 1462E? Not sure. But the solution is DP.
Now, let's consider if there is any possibility of more efficient algorithm. This is fine.
Now, final answer.
But one more thought: The DP we designed uses 26 letters. But the problem only requires lowercase English letters, so 26 is fine.
Now, is there any scenario where we need to consider that the final string must also have no palindrome substring of length >1, which also includes palindromes that are not necessarily of length 2 or 3 but could be of length 4 that are not captured? Already captured.
Thus final.
Now, final code.
I'll now produce final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
int n = s.size();
if (n == 1) {
cout << "0\n";
continue;
}
vector a(n);
for (int i = 0; i < n; ++i) a[i] = s[i] - 'a';
int dp[26][26];
for (int i = 0; i < 26; ++i)
for (int j = 0; j < 26; ++j)
dp[i][j] = INF;
// base: first two positions
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < 26; ++j) {
if (i == j) continue;
dp[i][j] = (i != a[0]) + (j != a[1]);
}
}
// process remaining characters
for (int idx = 2; idx < n; ++idx) {
int cur = a[idx];
int min1[26], min2[26], minChar[26];
// for each possible last character b, find two best previous a
for (int b = 0; b < 26; ++b) {
int m1 = INF, m2 = INF, c1 = -1;
for (int a_ = 0; a_ < 26; ++a_) {
if (a_ == b) continue;
int v = dp[a_][b];
if (v < m1) {
m2 = m1;
m1 = v;
c1 = a_;
} else if (v < m2) {
m2 = v;
}
}
min1[b] = m1;
min2[b] = m2;
minChar[b] = c1;
}
int ndp[26][26];
for (int i = 0; i < 26; ++i)
for (int j = 0; j < 26; ++j)
ndp[i][j] = INF;
for (int b = 0; b < 26; ++b) {
int m1 = min1[b];
int m2 = min2[b];
int forbid = minChar[b];
for (int c = 0; c < 26; ++c) {
if (b == c) continue;
int best = (forbid != c) ? m1 : m2;
// best is guaranteed to be finite
int cost = (c != cur) ? 1 : 0;
ndp[b][c] = best + cost;
}
}
// copy back
for (int i = 0; i < 26; ++i)
for (int j = 0; j < 26; ++j)
dp[i][j] = ndp[i][j];
}
int ans = INF;
for (int i = 0; i < 26; ++i)
for (int j = 0; j < 26; ++j)
if (i != j)
ans = min(ans, dp[i][j]);
cout << ans << "\n";
}
return 0;
}