Problem Description
Given a string s consisting of lowercase English letters, pair characters that are mirrors of each other (where the mirror of a letter is defined as the corresponding letter when the alphabet is reversed, e.g., mirror of 'a' is 'z' and mirror of 'b' is 'y'). Process the string from left to right. For each index i, find the closest unmarked index j (with j < i) such that s[j] is the mirror of s[i]. Mark both indices, add (i - j) to the total score, and continue. Return the total score after processing the entire string.
Key Insights
- The mirror of a given letter c can be computed using the formula: mirror(c) = char('z' - (c - 'a')).
- Process the string in a single pass (left-to-right) for an O(n) time solution.
- Use a hash table (or dictionary) to store unpaired indices for each letter. Stacks (LIFO) for each letter allow retrieving the closest unmarked index quickly.
- When encountering a character, check if there exists an unpaired matching mirror character; if so, pop that index and add the difference to the score. Otherwise, save the current index for a potential future match.
- Greedy pairing ensures that we always select the closest unmarked mirror index.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string
Space Complexity: O(n), to store indices in the hash table in the worst case
Solution
The solution uses a hash table where keys are characters and values are stacks (lists or similar data structures) that store indices of unpaired occurrences of that character. For each character in the string, compute its mirror. If a matching unpaired mirror exists (i.e., there is an index in the stack corresponding to the mirror letter), pop that index, calculate the distance, and add it to the total score. If not, push the current index into the stack for later matching. This greedy approach ensures pairing with the closest mirror occurrence and guarantees an optimal solution.