Please read the new rule regarding the restriction on the use of AI tools. ×

priyanshbarya's blog

By priyanshbarya, history, 11 months ago, In English

Problem: Let us define the cost of string s to be the number of characters to be replaced such that the resulting string is rearrangeable to palindrome.

For e.g., let s="abc", the cost is 1 since we can change b to a (or b to c), and the resulting string will be rearrangeable to a palindrome.

You are given a string s (1<=length<=1e5). Find the sum of the cost of all the substrings.

Please help me out with this problem.

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
11 months ago, # |
  Vote: I like it 0 Vote: I do not like it

For a palindrome string with even length, the number of occurrences of each character must be even. For a palindrome with odd length, the number of occurrences of each character must be even, except the character in the middle is odd. So you can maintain a frequency array to solve this problem.

  • »
    »
    11 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    sorry I misunderstand the problem. It says find total cost for all substrings

»
11 months ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

Someone else asked this problem, seemed a bit strange. Anyway, the problem is pretty simple (or should I say mechanical):

  1. Define the parity of a string $$$s$$$ (say $$$p(s)$$$) as the number of characters that have an odd number of occurrences in it. The cost for a substring $$$s[i..j]$$$ is $$$\lfloor p(s[i..j])/2 \rfloor$$$. When taking the sum of this over all substrings, note that it equals $$$\sum p(s[i..j])/2 - |\{(i, j) \mid p(s[i..j]) \text{ is odd}\}|/2$$$.
  2. The first sum is easy — for each character from $$$a$$$ to $$$z$$$, find the number of substrings it contributes to — i.e., the number of substrings where it occurs an odd number of times. To do this, store positions of each character and use prefix/suffix sums for odd/even occurrences.
  3. For the second part, note that if we extend a substring to the right by 1, then the parity of the substring changes. So, let's pair up all such substrings, and there will remain some suffix substrings, for which parity can be computed in $$$O(n)$$$ time by moving from right to left (use bitmasks and popcount). Since the total number of substrings is known, and the difference between the number of substrings with odd parity and even parity is known, we can count the number of substrings with odd parity by solving these two linear equations.