Ctrl K

Mirror Letter Pairing Score

Medium
The **mirror** of an English letter is the letter in the same place once the alphabet is reversed: a mirrors z, b mirrors y, m mirrors n, and the other way round. You get a string word. At first no position is taken. Walk through the string from left to right; for each position i, find the **nearest** free position j < i that holds the mirror of word[i]. If there is one, mark both positions as taken and add i - j to the score; otherwise just move on. Return the final score (it starts at 0).
Example 1
word='bayyzb' → 7

The mirror of b is y and the mirror of a is z. At position 2 the y finds the free b at 0: +2. At 3 the second y looks for a b, but none is free. At 4 the z finds the a at 1: +3. At 5 the b looks for a y and finds the free one at 3: +2. Total 7.

Example 2
word='hello' → 1

The mirrors of h, e, l, o are s, v, o, l. At position 4 the o finds the nearest free l at position 3: +1. Total 1.

Example 3
word='mn' → 1

m and n mirror each other, and the pair scores 1.

Constraints
  • 1 ≤ len(word) ≤ 10⁵
  • word consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsErase the Pattern Until It Is Gone MediumCrashes on One Lane MediumStar as Backspace MediumPrinter With a Holding Tray MediumStars Eat the Smallest Letters Medium
loading Python…
Input
word='bayyzb'
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 77 tests on the server, hidden ones included.