KatInterview

Count Character Mismatches Across All Palindrome Mirrors

StringsAuto-graded · 24 test cases
MediumAuto-gradedStringscombinatoricsstring-algorithmsoptimization

Last updated

Tests the ability to reframe a quadratic substring enumeration into a pair-centric counting problem with geometric weight calculations.

You are given a string sequence containing only the characters A, C, G, and T.

For any contiguous substring of sequence, we can measure how far it is from being a palindrome by counting the number of positions that would need to change. Specifically, for a substring of length m, we compare characters at mirror positions: the first with the last, the second with the second-to-last, and so on, stopping at the middle. Each pair of mirror positions that holds different characters contributes 1 to the cost.

Your task is to calculate the total cost across every possible contiguous substring of sequence.

Constraints:

  • 1 ≤ len(sequence) ≤ 5000
  • sequence contains only the characters A, C, G, T
  • The result will fit in a 64-bit signed integer

Examples

Example 1

Input: total_mismatch_cost('ACGT')

Output: 7

Example 2

Input: total_mismatch_cost('AAAA')

Output: 0

Example 3

Input: total_mismatch_cost('ACCA')

Output: 4

Example 4

Input: total_mismatch_cost('AGCTAG')

Output: 20

Hints

Hint 1

Instead of iterating over all substrings and checking each one, think about the contribution of each pair of positions in the original string.

Hint 2

For two positions i and j where sequence[i] != sequence[j], count how many substrings include both positions as a mirror pair.

Hint 3

A pair at positions i and j forms a mirror in a substring [L, R] when they are equidistant from the substring's center: i - L == R - j.