Total Palindrome Substring Cost
Learn this problemProblem statement
Some data scientists are building a utility to analyze palindromic trends in the DNA sequencing of a string.
The palindrome transformation cost of a string is defined as the minimum number of characters that need to be changed so that the string can be rearranged to form a palindrome. For example, the palindrome transformation cost of "aabcd" is 1, since changing 'd' to 'c' makes "aabcc", which can be rearranged to "acbca".
Given a string dna, find the total sum of palindrome transformation costs of all substrings of dna.
Note: A palindrome is a sequence that reads the same backward as forward. For example, "z", "aba", and "aaa" are palindromes, but "xy" and "rank" are not.
Function
totalPalindromeSubstringCost(dna: String) → longComplete the function totalPalindromeSubstringCost in the editor below. The function returns the total sum of palindrome transformation costs across all substrings.
totalPalindromeSubstringCost has the following parameter:
dna: a string
Examples
Example 1
dna = "abca"return = 6For dna = "abca", the single-character substrings "a", "b", "c", and "a" each have cost 0.
"ab"has cost1; change'b'to'a'to make"aa"."abc"has cost1; change'b'to'c', then it can be rearranged to"cac"."abca"has cost1; change'b'to'c'to make"acca"."bc"has cost1; change one character to match the other."bca"has cost1; change'c'to'a', then it can be rearranged to"aba"."ca"has cost1; change'c'to'a'to make"aa".
Therefore the total is 1 + 1 + 1 + 1 + 1 + 1 = 6.
Example 2
dna = "acbaed"return = 19For dna = "acbaed", the single-character substrings "a", "c", "b", "a", "e", and "d" each have cost 0.
- All substrings of length
2, namely"ac","cb","ba","ae", and"ed", have cost1. "acb","cba","bae", and"aed"have cost1; one character can be changed so the substring can be rearranged into a palindrome."acba"has cost1; for example, change'b'to'c'to make"acca"."acbae"has cost1; change'c'to'e', then it can be rearranged to"aebea"."acbaed"has cost2; change'c'to'e'and'b'to'd', then it can be rearranged to"aeddea". Similarly,"cbae","baed", and"cbaed"each have cost2.
Therefore the answer is 5 * 1 + 4 * 1 + 1 + 1 + 4 * 2 = 19.
Example 3
dna = "wwwww"return = 0All substrings of "wwwww" are already palindrome-like because every character is the same, so every substring has cost 0. The total sum is 0.
Constraints
1 <= |dna| <= 2 * 10^5- The string
dnacontains lowercase English letters only.
More Uber problems
- Last Truck to Leave the LaneOA · Seen Jul 2026
- Chain of CommandOA · Seen Jul 2026
- Jump Game with Prime-3 StepsOA · Seen Jun 2026
- Earliest Time All Users Are ConnectedPHONE SCREEN · Seen May 2026
- Tournament Rounds by RankPHONE SCREEN · Seen May 2026
- Farthest Seat AssignmentONSITE INTERVIEW · Seen May 2026
- Convex Function MinimizationPHONE SCREEN · Seen May 2026
- Maximal Square AreaONSITE INTERVIEW · Seen May 2026