After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 ≤ N ≤ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
aa + bb → abba.
The second example:
aab + abcac = aababcac → aabccbaa
aab + aa = aabaa
abcac + aa = abcacaa → aacbcaa
dffe + ed = dffeed → fdeedf
dffe + aade = dffeaade → adfaafde
ed + aade = edaade → aeddea
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to count pairs (i, j) with i < j such that there exists a permutation of s_i + s_j that is a palindrome.
Observation: A string (or multiset of characters) can be permuted to form a palindrome if and only if at most one character has odd count. Equivalent: The parity vector (bitmask of length 26 indicating odd/even count) can have at most one bit set. More formally, let freq[26] counts. After merging two strings s_i and s_j, we get concatenation. The concatenated string's character counts are sum of counts of s_i and s_j. So parity of total count for each character is XOR of parities of individual strings (since parity of sum mod 2). So the parity mask for concatenated string is mask_i XOR mask_j (where mask_i is bitmask of odd counts in s_i). The concatenated string can be permuted into a palindrome iff popcount(mask_i XOR mask_j) <= 1.
Thus condition: popcount(mask_i XOR mask_j) <= 1.
We need to count unordered pairs (i,j) with i<j such that popcount(mask_i XOR mask_j) <= 1.
N up to 100k, total characters up to 1e6. So we can compute mask for each string efficiently. Then we need to count pairs among N masks such that Hamming distance <= 1.
That is: pairs where masks are equal (distance 0) OR differ by exactly one bit (distance 1).
Because popcount(mask_i XOR mask_j) can be 0 or 1; note that 2 could be >1 so we only accept 0 or 1.
Thus total pairs = sum over frequencies of mask: C(cnt[mask],2) + sum over all pairs of masks that differ by exactly one bit: cnt[mask] * cnt[mask ^ (1<<b)] for each bit b (0..25). But careful: when counting differing by one bit, we should count each unordered pair only once. Since (mask, mask') with mask' = mask xor (1<<b) for some b, the condition is symmetric. So we can iterate over each mask, for each bit b, add cnt[mask] * cnt[mask xor (1<<b)], but that will count each pair twice (once from mask and once from mask')? Let's examine: For two masks A and B such that B = A xor (1<<b). When iterating over mask = A and bit b, we add cnt[A]*cnt[B]. When iterating over mask = B and bit that flips back to A (same bit b) we add cnt[B]*cnt[A]. That would double count. So we need to either restrict to only one direction: e.g., iterate over mask and bit, but only if mask < mask xor (1<<b) (or some ordering) to avoid double counting. Or we can compute sum over all unordered pairs by iterating bits and masks and then divide by 2. But since N up to 100k, number of distinct masks at most 2^26 = 67 million but that's too large to iterate over all masks. But we only have masks that appear among strings, which at most N = 100k distinct masks (could be up to N). So we can use a hashmap (dictionary) to store counts per mask.
Then to count pairs with distance 1: For each present mask m, for each bit b (0..25), compute neighbor = m xor (1<<b). If neighbor exists in the map, then add cnt[m] * cnt[neighbor]. This counts each unordered pair twice (once from m, once from neighbor). So after summing, we can divide by 2. But careful: Might double count also when m == neighbor? That cannot happen because flipping a bit changes the mask unless the bit was 0? Actually m xor (1<<b) == m iff (1<<b)=0, not possible. So neighbor != m. So each unordered pair appears exactly twice. So we can compute total = sum_{m} cnt[m](cnt[m]-1)/2 + (1/2) sum_{m} sum_{bit} cnt[m] * cnt[neighbor]. However, we must be careful not to overflow; use 64-bit integers.
Alternatively, we can only add when m < neighbor (some ordering) to avoid double counting. But we'd need to compare masks as integers. So we can loop over each mask in map, for each bit b, compute neighbor = m xor (1<<b). If neighbor > m (as integer), then add cnt[m] * cnt[neighbor]. That yields each unordered pair once. That's more efficient and avoids floating point. So we'll do that.
Thus solution: compute mask for each string; map mask -> count. Then initialize ans = 0. For each (mask, cnt) in map: ans += cnt*(cnt-1)//2. Then for each (mask, cnt) in map: for b in 0..25: neighbor = mask ^ (1<<b). If neighbor > mask and neighbor in map: ans += cnt * map[neighbor].
But is this condition correct? For distance 0 we already added. For distance 1 we count each unordered pair exactly once by requiring neighbor > mask.
Edge case: what about masks that differ by one bit but also maybe the same mask? Not possible.
Thus answer computed.
But wait: Are we missing anything? The condition for palindrome after concatenation and permutation is popcount(mask_i XOR mask_j) <= 1. That's necessary and sufficient. So answer = number of pairs with Hamming distance <=1. So above algorithm works.
Let's test examples.
Example1:
Strings: "aa", "bb", "cd"
Compute masks:
"aa": counts: a:2 (even->0), others 0 -> mask=0.
"bb": similarly mask=0? b:2 even -> mask=0.
"cd": c:1 odd => bit2 set? Actually a=0,b=1,c=2,d=3,... So c (index2) -> 1<<2=4; d (index3) -> 1<<3=8; mask=4+8=12. So map: 0:2, 12:1.
Pairs: (0,0): C(2,2)=1. Also distance 1 between mask 0 and mask 12? popcount(0 xor 12)=popcount(12)=2 (bits 2 and 3) =>2>1, not allowed. So only one pair: (aa,bb). Output 1. Good.
Example2:
Input:
6
aab
abcac
dffe
ed
aa
aade
We need to compute masks.
Compute manually:
aab: a:2, b:1 -> odd? a even, b odd => mask has bit for b (1). 'b' index 1 -> 1<<1=2? Actually a=0,b=1,c=2,d=3,e=4,f=5,... So b -> bit1=2. So mask aab = 2.
abcac: a:2 (even), b:1 (odd), c:2 (even) -> odd only b? Actually also? Let's count: a appears twice, b once, c appears twice? "abcac": letters: a,b,c,a,c -> a:2, b:1, c:2 -> only b odd. So mask=2 again (bit1).
dffe: d:1, f:2? Actually "dffe": d:1, f:2, e:1 -> odd: d and e. So mask bits: d index3 -> 1<<3=8, e index4 -> 1<<4=16, total=24.
ed: e:1, d:1 -> odd both => mask = 8+16=24 again.
aa: a:2 -> mask=0.
aade: a:2, d:1, e:1 -> odd: d and e => mask=8+16=24? Actually a even, d odd, e odd => mask=24.
So masks: aab:2, abcac:2, dffe:24, ed:24, aa:0, aade:24.
Counts: mask0:1, mask2:2, mask24:3.
Now compute pairs with distance<=1:
Distance0: within same mask: mask2: C(2,2)=1; mask24: C(3,3)=3; mask0: C(1,1)=0? Actually 1 choose2=0. So 1+3=4.
Distance1: need popcount(mask xor other) =1.
Check pairs between mask0 (0) and mask2 (2): popcount(0 xor 2)= popcount(2)=1 -> valid. So pairs: cnt0 * cnt2 = 1*2 = 2.
Between mask0 and mask24: popcount(0 xor 24)= popcount(24)=2 -> not valid.
Between mask2 and mask24: popcount(2 xor 24)=popcount(26)=? 2 = binary 000010, 24=11000? Actually 2 decimal = 0b000010 (bit1), 24 = 0b011000? Let's compute: 24 = 16+8, bits 3 and 4? Actually indices: 0:a,1:b,2:c,3:d,4:e. So 8 (2^3) and 16 (2^4) => bits 3 and 4 set. So binary: bits 3 and 4 => bits positions 3 and 4 => 11000? Actually from LSB bit0: b0:0, b1:0? Wait careful: 2^3=8, 2^4=16. So bit3 and bit4 set => binary number: ... 16+8=24 -> representation: bit4=1, bit3=1, others 0. So 24 = 00011000 in bits 0-7? Actually bits: 0:0,1:0,2:0,3:1,4:1 => 24 = 2^3+2^4. So XOR with 2 (bit1) gives bits: 1,3,4 set => 2+8+16=26, popcount=3 >1. So not valid.
Also check mask2 with itself already counted. Also check mask24 with mask? Is there any mask that differs by one bit from 24? For example, flipping bit3 yields 24 xor 8 = 16, which is mask? 16 corresponds to only e odd? But we don't have mask16 present. Flipping bit4 gives 8, not present. Flipping any other bit yields some masks not present. So no distance1 between 24 and others.
So total pairs = 4 + 2 = 6. That matches output.
So algorithm works.
But wait, we need to be careful about the total length of strings: up to 1e6, so computing mask per string by counting chars is fine.
Now, constraints: N up to 100k, distinct masks at most 100k. For each mask, we iterate 26 bits to check neighbors. So total operations ~ 100k * 26 = 2.6 million, which is fine.
Memory: map of size up to 100k entries.
Thus solution seems straightforward.
But is there any subtlety? Let's double-check: The condition "at least one permutation of the concatenation of the two strings is a palindrome." That's exactly the condition we used. However, is there any possibility where the concatenated string itself is not a palindrome but can be rearranged? Yes, we used parity condition. So fine.
But wait: The problem states "at least one permutation of the concatenation of the two strings is a palindrome." So we consider all permutations. The condition is exactly as we used.
Potential nuance: Could there be a case where the concatenation string is not a palindrome but a permutation exists, but we might think it's not allowed? No, because we used parity condition which is necessary and sufficient for existence of a palindrome permutation (for any string). So correct.
Thus answer = number of pairs with popcount(mask_i XOR mask_j) <= 1.
Now implementation details:
Read N.
For each of N strings, compute mask: initialize mask = 0; for each character c in string: mask ^= (1 << (ord(c)-ord('a'))). Because toggling parity. This yields mask with bits set for characters with odd count.
Store counts in dictionary (unordered_map in C++, dict in Python). Since N up to 100k, Python will be fine (2.6 million operations). But careful: Python's ints are arbitrary precision; using bit masks up to 2^26, fine. Use dict.
Then ans = 0 (use Python int).
For each mask, cnt in dict.items(): ans += cnt * (cnt - 1) // 2
Then for each mask, cnt in dict.items(): for bit in range(26): neighbor = mask ^ (1 << bit); if neighbor > mask and neighbor in dict: ans += cnt * dict[neighbor]
Print ans.
But double-check: When counting distance1, do we need to consider also the case where the total mask has popcount 0? That's distance0 already. And distance1 condition is as above.
Potential edge: Could there be pairs where mask_i XOR mask_j yields 0 (i.e., same mask) but also the concatenated string's palindrome condition is satisfied, obviously. So included.
All good.
But let's consider if any further optimization needed? N=100k and strings total length 1e6, fine.
Testing some corner cases:
N=1: no pairs, answer 0.
All strings empty? Possibly empty strings? The problem says strings consist of only small letters; maybe empty? Not specified that strings are non-empty, but typical contest might allow empty? But let's assume they could be empty? Usually string may be empty? In problems, they sometimes include empty strings but "consisting of lowercase English letters" could include empty? Usually they say "string of lowercase English letters", which often implies non-empty? But sometimes empty is allowed. To be safe, treat empty string as mask=0. Works fine.
Large N with many identical masks: counting C(cnt,2) works.
When counting neighbors, we do if neighbor > mask to avoid double count. But careful: In Python, dictionary keys are ints, comparision works. However, if we have mask and neighbor where neighbor > mask, but we also have both present, we count once. Good.
But is there any case where mask and neighbor differ by one bit but neighbor < mask, and we skip it, but later when iterating neighbor (which > mask) we will count it? Actually if neighbor < mask, then when iterating neighbor as mask, neighbor will be > mask? Let's see: Suppose mask A and mask B = A xor (1<<b). If A > B, then when iterating mask = B, neighbor = B xor (1<<b) = A, and since A > B, the condition neighbor > B is true, so we will count B * A. So each unordered pair counted exactly once. Good.
But careful: For each mask, we loop over all 26 bits, and each pair might be considered multiple times if there are multiple bits that connect them? However, two distinct masks differ by exactly one bit, so only one bit difference. So for a given unordered pair (A,B) with B = A xor (1<<b), there is exactly one bit b. So it will be counted exactly once when we are at the smaller of A and B and check that bit. So no double counting.
Thus algorithm is correct.
But wait: Could there be pairs where mask_i XOR mask_j = 0 (identical masks) but also the concatenated string after permutation yields a palindrome? That's covered by distance 0. But note: Even if two strings have same parity mask, it is guaranteed that the concatenated string can be permuted into a palindrome? Let's verify: If mask_i == mask_j, then mask_i XOR mask_j = 0, popcount 0 <=1, so condition satisfied. So yes, any pair with same parity mask automatically qualifies. But is it always true? For a multiset of characters formed by concatenating two strings with identical parity mask, the overall counts for each character are sum of counts. The parity of each count is even because the parity mask XOR is 0 meaning each character's total parity is even (since parity_i + parity_j mod2 = 0). But careful: The parity mask indicates which characters have odd count in each string individually. If two strings both have odd count for a character, then the total count for that character is odd+odd = even? Actually odd+odd = even, parity 0. If both even, total even. If one odd one even, total odd. So if masks are equal, then for each character, either both odd or both even. So total parity is even for each (odd+odd=even, even+even=even). So all characters have even total count. Thus the concatenated multiset can be permuted into a palindrome (in fact, all even, can form palindrome of even length). So correct.
Similarly, if masks differ by exactly one bit, then the total parity mask has exactly one bit set, meaning all characters except one have even counts, one character has odd count. So palindrome possible.
Thus condition is exact.
Therefore solution stands.
Now complexity: O(total length + N * 26) which is fine.
Potential pitfalls: The input size: total characters up to 1,000,000. Python reading lines with sys.stdin should handle. Use sys.stdin.read().splitlines() maybe.
Edge Cases: Could there be strings longer than typical? Not a problem.
Now we must output answer as integer.
Let's test manually with given examples.
Example1: N=3, strings: aa, bb, cd -> we computed ans=1.
Example2: we computed ans=6.
Another test: N=2, strings: "a", "a". masks: each 'a' odd -> mask=1 (bit0). So cnt=2, ans = 1 (since distance0). Permutation of "aa" is "aa", palindrome, ok.
N=2: "a", "b". masks: 1 and 2 (bit0 and bit1). Distance: 1 xor 2 = 3 -> popcount=2 >1, so not allowed. But is there a permutation of "ab" that is palindrome? "ab" cannot be palindrome because length 2, need both chars same. So correct.
N=2: "ab", "ba". Let's compute masks: "ab": a odd, b odd => mask = 1+2=3. "ba": also mask=3. Distance0 => allowed. Concatenation "abba"? Actually "ab"+"ba" = "abba" which is palindrome already. Permutation exists. So good.
N=2: "abc", "cba". Masks: each has a,b,c odd? Actually each letter appears once: a,b,c all odd => mask = 1+2+4=7. Distance0 => allowed. Concatenation "abccba"? Actually "abc"+"cba" = "abccba" which is palindrome. So fine.
N=2: "abcd", "efgh"? All letters odd each. masks: each has four bits set => masks not same and differ by multiple bits. Not allowed.
Seems correct.
Now, the problem mentions "at least one permutation of the concatenation of the two strings is a palindrome." Our condition includes both distance 0 and 1. But what about the possibility where the concatenated string has length 0? Two empty strings? mask=0 each. Distance0 => allowed. Palindrome? Empty string is trivially palindrome. So good.
One more nuance: Could there be cases where the concatenated string's total length is odd and the odd character count is one, but is it always possible to arrange into a palindrome? Yes.
Thus answer.
But wait, there is another nuance: The strings themselves are not necessarily of length >0. If we have a string with many characters and another with many, the parity condition is necessary and sufficient regardless of length.
Now I'll think if there is any hidden catch. Possibly the phrase "at least one permutation of the concatenation of the two strings is a palindrome" could be interpreted as we must consider concatenating the strings in the given order (i.e., s_i + s_j) and then permuting that concatenated string. That's exactly what we did because the multiset of characters is the union of the two strings regardless of order. So condition on multiset.
Thus solution correct.
Now implementation.
But caution: N up to 100k, total characters up to 1e6. We'll compute masks using XOR. The mask for a string is the parity of counts. So we can compute as we read each string.
Potential memory: storing all masks in a list is optional; we can directly update dict.
Pseudo:
import sys
def main():
data = sys.stdin.read().split()
if not data: return
it = iter(data)
n = int(next(it))
cnt = {}
for _ in range(n):
s = next(it)
mask = 0
for ch in s:
mask ^= (1 << (ord(ch) - 97))
cnt[mask] = cnt.get(mask, 0) + 1
ans = 0
for mask, c in cnt.items():
ans += c * (c - 1) // 2
for mask, c in cnt.items():
for b in range(26):
nb = mask ^ (1 << b)
if nb > mask and nb in cnt:
ans += c * cnt[nb]
print(ans)
if name == "main":
main()
Test with examples.
One more test: N=100k all empty strings => all mask=0, cnt=100000. ans = C(100000,2) = 100000*99999/2 = 4,999,950,000 which fits in 64-bit? Python int fine. Also distance1 with neighbors? none. So output that number.
But also we should consider that empty strings might not be present; but it's fine.
Now, but is there any scenario where the condition popcount(mask_i XOR mask_j) <= 1 is not sufficient? Let's consider very short strings? No.
Double-check reasoning: For a multiset of characters, being able to form a palindrome means at most one character has odd frequency. The total frequency for each character from concatenation is sum of frequencies of two strings. The parity of total frequency is parity_i XOR parity_j (since parity of sum mod2 = parity_i XOR parity_j if we treat 1 for odd, 0 for even). So total parity mask = mask_i XOR mask_j. Condition: popcount(mask_i XOR mask_j) <= 1. So correct.
Thus solution is simple.
But wait, there is also possibility that we could swap the order of concatenation (i.e., s_j + s_i) but the problem says "concatenation of the two strings" but doesn't specify order. Typically concatenation order is not defined; but pair (i,j) is unordered, so we consider any concatenation order? The condition says: "at least one permutation of the concatenation of the two strings is a palindrome." Usually concatenation of two strings might mean first string followed by second string, but since we can permute the entire string arbitrarily, order of concatenation doesn't matter: The multiset of characters is the same regardless of order. So condition only depends on the multiset. So fine.
Thus answer.
Now, I recall a known problem from Codeforces: "Palindrome Pairs". Actually there is a well-known problem: given a list of strings, count pairs such that their concatenation (in some order) forms a palindrome. But there, the condition is that the concatenated string (without permutation) is a palindrome. That's different. This problem explicitly allows permutation of concatenated string. So it's easier.
But wait, is there a nuance: "at least one permutation of the concatenation of the two strings is a palindrome." Could also be interpreted as: we are allowed to permute the characters of the concatenated string (i.e., reorder arbitrarily) to obtain a palindrome. That's what we used.
Thus solved.
But given constraints, O(N * 26) is fine.
But we need to be careful: In Python, iterating over dict items and then inner loop over 26 bits, with neighbor existence check via dict lookup (which is O(1) average) is fine.
Potential improvement: We could precompute for each mask its neighbors, but not needed.
Now let's confirm with second example: we got 6.
Now, is there any chance that a pair counted where the concatenated string's permutation palindrome condition is satisfied but our mask condition fails? Could there be a scenario where total counts have more than one odd count but still can form a palindrome? No, because for a palindrome, the string must read same forward and backward. For even length, all character counts must be even. For odd length, exactly one character count must be odd. So condition is strict.
Thus fine.
Now implement.
But wait, we might need to consider large answer: up to C(100000,2) ≈ 5e9, fits in 64-bit but Python int fine.
What about s1="a", s2="b", s3="ab"? masks: "a":1, "b":2, "ab":1^2=3. Pairs: (1,2): popcount(3)=2 no; (1,3): popcount(1 xor 3 =2) = popcount(2)=1 yes; (2,3): popcount(2 xor 3 =1) =1 yes. So ans=2. Check manually: "a"+"ab" = "aab" can be permuted to "aba"? Actually "aab" counts: a:2,b:1 -> one odd -> can permute to "aba" palindrome. So yes. "b"+"ab" = "bab" -> "bab" palindrome? "bab" is palindrome itself. So yes. So ans=2. Our method: cnt: mask1:1 from "a", mask2:1 from "b", mask3:1 from "ab". distance0: none because each cnt=1 =>0. distance1: for mask=1 (c=1), neighbors: flip bits gives mask=0,2,4,8,...; only mask2 present and >1? 2>1 so ans += 11=1. For mask=2, neighbors: mask=3? Actually 2^1=3? That's flipping bit0 gives 3; but mask3 is present and >2? 3>2 so ans += 11=1. For mask=3, neighbors: flipping bits: 3^1=2 (2<3 not counted), 3^2=1 (1<3 not counted), etc. So total ans=2. Good.
Now edge: duplicate masks with distance0: we count each pair once.
Now potential pitfall: Counting distance1 when neighbor > mask ensures we don't double count, but what if mask == neighbor? That's impossible. So fine.
Now, what about the scenario where mask_i XOR mask_j = 0 but the concatenated string can't be permuted into a palindrome due to something else? No.
Thus final answer.
But maybe there is a twist: The problem says "at least one permutation of the concatenation of the two strings is a palindrome." Could it be that we are allowed to permute the two strings individually before concatenating? No, says "permutation of the concatenation", i.e., of the resulting string.
Thus we are good.
Now, to ensure we are not missing any nuance about "permutation" meaning we can reorder characters arbitrarily, but maybe we cannot break the boundary between the two strings? The phrase "permutation of the concatenation" suggests we take the concatenated string and then permute its characters. So that's exactly what we consider.
Thus solution.
Now, let's think about performance: For each string, we compute mask by XOR each character. That's O(total length) = 1e6. Then we have at most 100k distinct masks. For each, we loop 26 bits, so 2.6M operations. Each operation does dictionary lookup. That's fine.
However, note that we may have many identical masks, but we still only iterate over distinct masks. So total loops ~ distinct_masks * 26 <= 100k*26 = 2.6M.
Thus Python implementation should run under 1 second? Possibly 0.5-1 sec. The input reading and mask computation also O(1e6) which is fine.
But note: In Python, using bit operations and dictionary lookups is fast enough. However, we should avoid using for ch in s: mask ^= (1 << (ord(ch)-97)) for each string because that's also okay.
But there might be micro-optimizations: Precompute bit values for each letter: bit = [1<<i for i in range(26)], but not necessary.
Now, we also need to consider that total characters up to 1e6, but strings might be read line by line with trailing newline. Use sys.stdin.buffer.read().split() to get bytes? But can use sys.stdin.read().split() as above.
Potential memory: reading all strings into list of strings might take memory ~ total characters + overhead, but total characters 1e6 plus overhead for list of 100k strings, that's okay.
Alternatively, we could process line by line using sys.stdin.readline to avoid storing all strings; we only need mask counts, not the strings. So we can read line by line. But using read().split() is simpler.
But careful: The input lines may contain spaces? No, strings consist only of lowercase letters. So split works.
But note: The first line is N, then N lines each containing a string. Some strings might be empty? If empty, reading via split() would skip empty lines because split() splits on whitespace and discards empty strings. So if there is an empty string line, it would be lost. For example, if a line is just a newline (empty string), split() would not return it. So we cannot use split() if empty strings are allowed. Do we need to handle empty strings? The problem statement says "strings which consist of only small letters of the alphabet." That implies non-empty? But it's ambiguous; but usually strings can be empty? Typically in programming contests, strings can be empty? Many problems explicitly say non-empty, but here they didn't say non-empty. However, the phrase "consist of only small letters" could be interpreted that if the string exists, it contains only small letters, but the string could be empty? Usually they would say "consisting of lowercase English letters" and not mention empty; many problems allow empty strings but they would state "possibly empty". I'd guess they intended strings to be of length at least 1, because total number of characters is less than 1,000,000, and they wouldn't consider empty strings. But to be safe, we should handle empty strings correctly. If empty strings are possible, using split() would skip them, resulting in wrong count. Better to read lines with sys.stdin.buffer.read().splitlines() and process accordingly.
Let's read the first line, then read exactly N lines. We can use sys.stdin.readline in a loop. That's safer.
Implementation:
import sys
def main():
input = sys.stdin.readline
n = int(input())
cnt = {}
for _ in range(n):
s = input().strip() # strip newline
# s may be empty? if line is just newline, strip returns ''
mask = 0
for ch in s:
mask ^= (1 << (ord(ch) - 97))
cnt[mask] = cnt.get(mask, 0) + 1
ans = 0
for mask, c in cnt.items():
ans += c * (c - 1) // 2
for mask, c in cnt.items():
for b in range(26):
nb = mask ^ (1 << b)
if nb > mask and nb in cnt:
ans += c * cnt[nb]
print(ans)
if name == "main":
main()
That's robust to empty strings.
Now test with empty string case: N=2, strings: "" and "". Both mask=0. cnt[0]=2. ans = C(2,2)=1. Works. If we used split, would get 0 lines after first, not good.
Thus use readline.
Now complexity: reading lines with .strip() will allocate a new string each time, fine.
Now, we should note that total characters up to 1e6, so reading line by line is fine.
Now, consider potential performance: Python's for ch in s: inside loop may be a bit slower but total 1e6 iterations is fine.
Now, one more nuance: The mask for each string is computed by XORing bits. But note: For long strings, the mask may become large up to 2^26-1. That's fine.
Now, final answer.
But wait: The problem description includes "at least one permutation of the concatenation" which we have used. However, I've just realized there might be another interpretation: The concatenation is fixed (s_i followed by s_j), and we can permute the characters of the resulting string (i.e., we can rearrange the characters arbitrarily). That's exactly what we used. Good.
Now, confirm with example: They gave example with "aab" and "abcac" concatenated -> "aababcac". Permutation "aabccbaa" exists. So condition satisfied.
Our mask for "aab": mask =? a:2 even, b:1 odd => mask bit1=2. "abcac": mask also 2. So distance0 => allowed. Indeed, they gave as pair.
Thus consistent.
Now, we need to output number of pairs.
Thus solution ready.
But is there any possibility of pairs where popcount(mask_i XOR mask_j) <= 1 but the concatenation cannot be permuted into a palindrome due to some other constraint? I think no.
Thus final answer.
Let's just double-check the logic: The total counts after concatenation are the sum of individual counts. So the condition for palindrome permutation is exactly that at most one character has odd total count. So that is popcount(mask_total) <= 1. Since mask_total = mask_i XOR mask_j, condition is popcount(mask_i XOR mask_j) <= 1. So it's necessary and sufficient.
Thus we are done.
Now, we must output answer.
Now, what about large N and many masks? Our algorithm counts pairs with distance1 by iterating over all masks and bits. That's fine.
But is there any need to also consider the possibility of masks that differ by zero bits (same) already counted.
Thus final.
One more check: Are we double counting distance1 when mask and neighbor differ by one bit, but neighbor > mask condition ensures we count each unordered pair once. But what if two masks are equal? That's not in distance1 counting.
All good.
Now, I'll produce final answer.
But before finalizing, think if there's any hidden optimization or edge-case: Could there be scenario where mask_i XOR mask_j has popcount 0 but the total length is odd? Actually if all characters have even counts, length is even, so palindrome exists (even length). So okay.
Now, let's test with a scenario: s_i empty, s_j "a". mask_i=0, mask_j=1. distance=1 => allowed. Concatenation = "a", which is palindrome. So good.
s_i empty, s_j "ab". mask_i=0, mask_j=1^2=3 (popcount=2) => not allowed. Concatenation "ab" cannot be palindrome. So fine.
Thus algorithm stands.
Now, implement.
Potential improvements: In Python, we might want to precompute an array of bit masks for each letter: bit = [1<<i for i in range(26)]. But not needed.
Now, answer.
But I recall a similar problem on Codeforces: "Palindromic characteristics" or "Palindrome Pairs", but there it's about concatenation without permutation. This one is simpler.
Let's quickly test with random small input via mental simulation:
N=4:
s1 = "ab"
s2 = "cd"
s3 = "abcd"
s4 = ""
Compute masks:
s1 "ab": a odd, b odd => mask=1+2=3.
s2 "cd": c odd, d odd => mask=4+8=12? Actually c index2 -> 4, d index3 ->8 => mask=12.
s3 "abcd": all odd => mask=1+2+4+8=15.
s4 "": mask=0.
Now pairs:
(3,12): xor=15 popcount=4>1 -> no.
(3,15): xor=12 popcount=2? 12 is 1100 popcount2 -> no.
(3,0): xor=3 popcount2 -> no.
(12,15): xor=3 popcount2 -> no.
(12,0): xor=12 popcount2 -> no.
(15,0): xor=15 popcount4 -> no.
Thus ans=0. But maybe (s1,s3) could form palindrome? "ab"+"abcd" = "ababcd", counts: a:2,b:2,c:1,d:1 -> two odd -> cannot. So correct.
Now add s5 = "ab" again. mask=3 count becomes 2. Then pairs: between the two "ab" masks: distance0 => 1. Also maybe with s4? mask3 vs mask0: distance=3 popcount2 -> no. So ans=1. Check: "ab"+"ab" = "abab" can be permuted to "abba" or "baab"? "abab": a:2,b:2 all even, so can be palindrome: "abba" or "baab". So correct.
Thus algorithm.
Now, maybe there is a case where concatenation of two strings yields a palindrome after permutation but their masks differ by more than 1? Let's think: Suppose s1 = "aabb", s2 = "cd". s1 mask: a:2 even, b:2 even => mask=0. s2 mask: c:1 odd, d:1 odd => mask=12 (bits2,3). xor=12 popcount=2 >1. But total counts: a:2,b:2,c:1,d:1 -> two odd -> cannot form palindrome. So correct.
What about s1 = "aab", s2 = "ab"? s1 mask=2, s2 mask=3 => xor=1 popcount=1 => allowed. total counts: a:2+1=3? Actually s1: a2,b1; s2: a1,b1 => total a3,b2 => a odd, b even -> one odd -> palindrome possible. So correct.
Now, are there cases where the two masks differ by two bits but the total odd count is still <=1? That would require that the odd bits cancel? Wait, if masks differ by two bits, xor has two bits set. That means that for those two bits, the parities are different (one string odd, the other even) leading to odd total for both? Let's analyze: For each character, total parity = parity_i XOR parity_j. So if the xor mask has two bits set, then there are exactly two characters for which total parity is odd. So total odd count = 2. So not possible to be <=1. Therefore condition is exact.
Thus solution complete.
Now we will write final solution with explanation.
But before final, consider constraints on memory and time. Python may handle up to 100k * 26 = 2.6M dict lookups, but each lookup is constant. However, we also have to compute mask for each string; total characters 1e6. So overall fine.
Potential Pitfall: Python's speed if we do for each mask: for b in range(26): neighbor = mask ^ (1 << b); if neighbor > mask and neighbor in cnt: ans += c * cnt[neighbor]. The dict lookup "neighbor in cnt" might be slower if many misses, but it's fine.
But note: There might be many masks (up to 100k). So loops: 100k * 26 = 2.6M. That's trivial.
Now, one more nuance: When mask is 0, flipping bits yields many neighbors. But many may not exist; we still compute and check dict. That's okay.
Thus final.
Now, we should provide answer with explanation of reasoning.
But the problem is from some contest? Could there be tricky part about total length? They said total number of characters in the input array will be less than 1,000,000. So sum lengths <= 1e6. Good.
Now, we can also solve using hashmap and counting.
Thus final answer.
But wait: The problem statement: "at least one permutation of the concatenation of the two strings is a palindrome." Could it be interpreted as we can permute the two strings (i.e., reorder them) before concatenation? That would be different: we could choose order of concatenation (s_i + s_j or s_j + s_i) and then maybe permute? But the phrase "permutation of the concatenation" suggests after concatenation we permute the resulting string. So order of concatenation is fixed? But pair (i,j) is unordered, but the concatenation could be either order? Usually we think of "concatenation of the two strings" without specifying order, but typically it means one after the other, but since pair is unordered, we might consider both orders? But since we can permute the final string, the order of concatenation doesn't matter: the multiset of characters is the same regardless of order. So it's irrelevant.
Thus fine.
Now, confirm with example: They give "aab" and "abcac" and say concatenation "aababcac", then permutation "aabccbaa". They didn't consider "abcacaab". But both produce same multiset. So it's fine.
Now, we should also consider the case where the strings are long and we compute mask using XOR; but we could also compute mask by counting mod 2. XOR is fine.
Now, let's think about potential overflow of integer when shifting 1 << 25. That's about 33 million, fits in Python int.
Now, we can write final code.
But before finalizing, let's run mental simulation on a large case to ensure no overflow in counting: Use Python ints unlimited.
Now, I'll write solution.
Now, also note: The answer may be up to about 5e9, which fits in 64-bit. But Python prints fine.
Thus final.
Now, potential alternate approach: using hashing but we already have.
Now, we can produce final answer.
Let's produce final response with explanation and code. We need to count unordered pairs (i, j) of strings such that some permutation of the concatenated string s_i + s_j is a palindrome.
A string can be rearranged into a palindrome iff at most one character occurs an odd number of times.
Let mask(x) be a 26-bit integer where the k‑th bit is 1 iff the k-th letter ('a' + k) appears an odd number of times in string x.
For the concatenation of two strings the total count of each letter is the sum of their counts, therefore the parity vector of the concatenated string is the xor of the two masks:
mask(s_i + s_j) = mask(s_i) XOR mask(s_j).
The condition “at most one odd character” is exactly popcount(mask_i XOR mask_j) ≤ 1.
Thus we have to count pairs with popcount(mask_i XOR mask_j) = 0 or 1.
Equivalently:
popcount = 0 → masks are equal.
popcount = 1 → masks differ in exactly one bit.
So we first compute the mask for each string and count how many strings have each mask.
Then:
For every mask, add C(cnt[mask], 2) (pairs with equal masks).
For every mask m and every bit b (0 … 25), let nb = m XOR (1 << b).
If nb exists in the map and nb > m (to count each unordered pair once), add cnt[m] * cnt[nb].
The result is the total number of palindrome pairs.
Complexity:
Computing masks: O(total length) ≤ 10⁶.
Counting: at most N distinct masks (≤ 10⁵), and for each we try 26 neighbours → ≤ 2.6 · 10⁶ operations.
Total time and memory are comfortably within limits.
python
import sys
def main() -> None:
input = sys.stdin.readline
n = int(input())
cnt = {}
for _ in range(n):
s = input().strip() # may be empty
mask = 0
for ch in s:
mask ^= 1 << (ord(ch) - 97)
cnt[mask] = cnt.get(mask, 0) + 1
ans = 0
# pairs with equal masks
for c in cnt.values():
ans += c * (c - 1) // 2
# pairs differing by exactly one bit
for mask, c in cnt.items():
for b in range(26):
nb = mask ^ (1 << b)
if nb > mask and nb in cnt:
ans += c * cnt[nb]
print(ans)
if __name__ == "__main__":
main()