Find Mirror Score of a String - Problem
You are given a string s containing lowercase English letters. Your task is to calculate the mirror score of this string through a fascinating character-matching process.
What is a mirror character?
Each letter in the English alphabet has a corresponding mirror letter when the alphabet is reversed:
• 'a' ↔ 'z'
• 'b' ↔ 'y'
• 'c' ↔ 'x'
• ... and so on
The Process:
- Start with a score of
0and all characters unmarked - Iterate through the string from left to right
- For each character at index
i, find the closest unmarked indexjwhere:
•j < i(must be to the left)
•s[j]is the mirror ofs[i]
• Neitherinorjis already marked - If such a
jexists, mark both indices and addi - jto your score - If no such
jexists, continue to the next character
Goal: Return the total score after processing all characters.
Input & Output
example_1.py — Basic Mirror Matching
$
Input:
s = "abcdef"
›
Output:
0
💡 Note:
No character has its mirror appearing before it in the string, so no matches are possible and the score remains 0.
example_2.py — Perfect Mirror Pairs
$
Input:
s = "za"
›
Output:
1
💡 Note:
When processing 'a' at index 1, we find its mirror 'z' at index 0. Score = 1 - 0 = 1.
example_3.py — Multiple Matches
$
Input:
s = "zaby"
›
Output:
2
💡 Note:
Processing 'a' at index 1: finds 'z' at index 0, score += 1. Processing 'y' at index 3: finds 'b' at index 2, score += 1. Total score = 2.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters only
- Each character can only be used in at most one pair
Visualization
Tap to expand
Understanding the Visualization
1
Dancers Enter One by One
Each dancer represents a character in the string, entering in sequence
2
Look for Compatible Partner
New dancer looks for most recent unpaired dancer with complementary style (mirror character)
3
Calculate Chemistry Score
If match found, pair them up and earn points equal to their entrance time difference
4
Optimal Stack Organization
Use separate waiting areas (stacks) for each dance style - newest person is always at the front of their line
Key Takeaway
🎯 Key Insight: Using stacks for each character type allows us to instantly find the closest unmatched mirror character in O(1) time, making the overall solution O(n) instead of O(n²).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code