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 index j such that j < i and s[j] is the mirror of s[i].
  • Then, mark both indices i and j, and add the value i - j to the total score.
  • If no such index j exists for the index i, 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
Mirror Score Problem: Input "za" → Output 1zaindex 0index 1Mirror of 'a' is 'z', Mirror of 'z' is 'a'Match found!Distance = 1 - 0 = 1Total Score: 1
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
Asked in
Microsoft 15 Amazon 12
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen