Taro Logo

Find Mirror Score of a String

#1 Most AskedMedium
0 views
Topics:
ArraysStringsStacks

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.

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 <= 105
  • s consists only of lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the input string `s`? Are we guaranteed that it contains only lowercase English letters?
  2. How should the distance between two indices `i` and `j` be calculated? Is it simply `i - j`?
  3. When looking for the "closest previously unmarked character", do we mean the most recent unmarked mirror character (i.e., the one with the maximum index strictly less than the current index `i`), and can already-marked characters be skipped?
  4. What should be returned if the input string is empty or if no characters can be marked at all (e.g., a string of all 'a's)? Should the score default to 0?
  5. If there are multiple previously unmarked mirror characters available that satisfy the condition, do we always pick the one with the highest index (the closest one), or is there any tie-breaking rule?

Brute Force Solution

Approach

To find the mirror score of a string using the brute force approach, we examine the text from the beginning to the end, looking for matching pairs of letters where one is the reverse alphabet counterpart of the other. We check every possible combination of earlier and later characters while following the specific rules for marking characters as used.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first letter of the string and note its position.
  2. Move step by step through the remaining letters to the right, searching for the first available letter that is the exact mirror opposite in the alphabet.
  3. If you find such a matching letter that has not already been used, calculate the distance between their positions, add that distance to your total score, and permanently mark both letters as used so they cannot be picked again.
  4. If you reach the end of the string without finding an unused mirror match for your current starting letter, simply move on to the next available letter in the string.
  5. Repeat this entire process of searching and pairing for every single letter from left to right until you have checked every possible combination.
  6. Finally, add up all the individual distances you collected along the way to get the final total score for the entire string.

Code Implementation

def calculate_mirror_score(input_string):
    total_mirror_score = 0
    string_length = len(input_string)
    used_character_flags = [False] * string_length

    alphabet_string = "abcdefghijklmnopqrstuvwxyz"

    for current_index in range(string_length):
        if used_character_flags[current_index]:
            continue

        current_character = input_string[current_index]
        mirror_character = alphabet_string[25 - alphabet_string.index(current_character)]

        # Search backwards for the closest unused mirror character to minimize distance
        matching_character_index = -1
        for backward_index in range(current_index - 1, -1, -1):
            if not used_character_flags[backward_index] and input_string[backward_index] == mirror_character:
                matching_character_index = backward_index
                break

        # Add distance and mark both characters as used if a valid mirror pair is found
        if matching_character_index != -1:
            distance_increment = current_index - matching_character_index
            total_mirror_score += distance_increment
            used_character_flags[current_index] = True
            used_character_flags[matching_character_index] = True

    return total_mirror_score

Big(O) Analysis

Time Complexity
O(n²) – For each character in a string of size n, the brute force approach scans the preceding unused characters from its current position back to the start of the string to find the first valid mirror match. In the worst case where no matches are found early or many characters must be checked, the outer loop runs n times while the inner search examines up to n elements. This sums up to roughly n * n/2 total comparisons across the string, which simplifies to O(n²).
Space Complexity
O(N) – To efficiently find the mirror matches and track which characters have been used as described in the steps, we utilize lists or hash maps to store indices of characters grouped by their alphabetical values. In the worst-case scenario where no characters are matched immediately, these collections will store up to N indices across the alphabet. Additionally, a boolean tracking array or visited set of size N is required to permanently mark characters as used. Therefore, the total auxiliary memory scales linearly with the input size N, simplifying to Big O notation of O(N).

Optimal Solution

Approach

The problem asks us to find the closest previously unmatched mirror character for each character encountered from left to right. Once a match is found, both positions are marked, and the distance between their indices is added to the total score. Using a stack for each alphabet letter allows us to greedily pair each character with its closest preceding unmarked mirror character in constant time.

Here's how the algorithm would work step-by-step:

  1. Create an array of 26 stacks, each dedicated to holding the indices of an unmarked letter.
  2. Initialize a running total score to zero.
  3. Iterate over the string with index and character.
  4. Calculate the mirror character offset by subtracting the current character's alphabetical index from twenty-five.
  5. If the stack for the mirror character is not empty, pop the most recent index and add the difference to the score.
  6. Otherwise, push the current index into the stack corresponding to the current character.
  7. Return the accumulated total score after checking all characters.

Code Implementation

def calculate_mirror_score(word_string: str) -> int:
    # Initialize stacks to store unmarked indices for each character
    character_stacks = [[] for _ in range(26)]
    total_score = 0
    # Iterate through the string to process each character and find matches
    for current_index, current_char in enumerate(word_string):
        char_code = ord(current_char) - ord('a')
        mirror_code = 25 - char_code
        # Check if an unmarked mirror character exists
        if character_stacks[mirror_code]:
            matched_index = character_stacks[mirror_code].pop()
            total_score += current_index - matched_index
        else:
            # Record the current index as available for future pairing
            character_stacks[char_code].append(current_index)
    return total_score

Big(O) Analysis

Time Complexity
O(n) – We iterate through the string of length n once. Each stack push and pop operation takes constant time, leading to an overall linear time complexity.
Space Complexity
O(n) – In the worst case where no characters are matched, every index is stored across the 26 stacks, requiring space proportional to the length of the string.

Edge Cases

Empty string input
How to Handle:
Return a score of zero immediately since no characters are available to process.
String with a single character
How to Handle:
The loop finishes without finding any pairs, resulting in a correct score of zero.
Characters with no matching mirror previously unmarked
How to Handle:
The algorithm leaves the current character unmarked and simply adds it to the tracking structure for future matches.
Multiple identical characters that could serve as mirrors
How to Handle:
Storing indices in a stack or list per character ensures we always pick the closest previously unmarked counterpart using LIFO order.
A character matching with its exact self (e.g., 'm' and 'n' near the alphabet center)
How to Handle:
The standard reverse mapping naturally pairs 'm' with 'n' correctly without causing self-matching bugs.
Maximum length strings up to the constraint limits with diverse characters
How to Handle:
An optimized hash map and stack approach achieves linear time complexity O(n) to process efficiently within time limits.
Large score values exceeding standard 32-bit integer limits
How to Handle:
Accumulate the total score using 64-bit integer types to prevent potential arithmetic overflow issues.
0/3 completed