Find Mirror Score of a String Problem
Description
LeetCode Problem 3412.
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 indicesiandj, 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.
Example 1:
Input: s = "aczzx"
Output: 5
Explanation:
- i = 0. There is no index j that satisfies the conditions, so we skip.
- i = 1. There is no index j that satisfies the conditions, so we skip.
- i = 2. The closest index j that satisfies the conditions is j = 0, so we mark both indices 0 and 2, and then add 2 - 0 = 2 to the score.
- i = 3. There is no index j that satisfies the conditions, so we skip.
- i = 4. The closest index j that satisfies the conditions is j = 1, so we mark both indices 1 and 4, and then add 4 - 1 = 3 to the score.
Example 2:
Input: s = "abcdef"
Output: 0
Explanation:
For each index i, there is no index j that satisfies the conditions.
Constraints:
1 <= s.length <= 10^5sconsists only of lowercase English letters.
Solution
Approach: Hash Table of Indices
The mirror of a letter x is chr('a' + 'z' - x). Scan s from left to right and keep, for each letter, the stack of indices that are still unmarked.
For the character x at index i, look at the stack of its mirror y. If it is not empty, the closest unmarked index j is its top: pop it and add i - j to the score (both j and i are now marked). Otherwise push i onto the stack of x.
Complexity: O(n) time, O(n) extra space.
from collections import defaultdict
class Solution:
def calculateScore(self, s: str) -> int:
d = defaultdict(list)
ans = 0
for i, x in enumerate(s):
y = chr(ord("a") + ord("z") - ord(x))
if d[y]:
j = d[y].pop()
ans += i - j
else:
d[x].append(i)
return ans