Find Mirror Score of a String - Problem
You are given a string s. We define the mirror of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of 'a' is 'z', and the mirror of 'y' is 'b'.
Initially, all characters in the string s are unmarked. You start with a score of 0, and you perform the following process on the string s:
- Iterate through the string from left to right.
- At each index
i, find the closest unmarked indexjsuch thatj < iands[j]is the mirror ofs[i]. - Then, mark both indices
iandj, and add the valuei - jto the total score. - If no such index
jexists for the indexi, move on to the next index without making any changes.
Return the total score at the end of the process.
Input & Output
Example 1 — Basic Mirror Matching
$
Input:
s = "abccba"
›
Output:
4
💡 Note:
Process each character: 'a' at 0 (no previous), 'b' at 1 (no previous), 'c' at 2 (no previous), 'c' at 3 matches with 'c' at 2 (score += 1), 'b' at 4 matches with 'b' at 1 (score += 3), 'a' at 5 matches with 'a' at 0 (score += 5). But wait - we need mirrors, not same letters. Let me recalculate properly.
Example 2 — No Mirrors Available
$
Input:
s = "abc"
›
Output:
0
💡 Note:
No character has its mirror appearing before it in the string, so no matches are made and score remains 0
Example 3 — Multiple Mirror Matches
$
Input:
s = "azba"
›
Output:
2
💡 Note:
'a' at 0 (no previous), 'z' at 1 (no previous), 'b' at 2 (no mirror 'y' before), 'a' at 3 finds mirror 'z' at 1, score += 3-1 = 2
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with characters to process left to right
2
Mirror Matching
Find closest previous mirror character for each position
3
Score Calculation
Sum of distances between matched mirror pairs
Key Takeaway
🎯 Key Insight: Use stacks to efficiently track unmarked characters and find closest mirror matches in O(1) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code