Skip to main content

Find Mirror Score of a String | Leetcode Problem | Complete CPP Solution | C++

 In this blog post, we will dive deep into solving the LeetCode problem: Find Mirror Score of a String. This is a medium difficulty problem that involves manipulating strings and understanding character relationships, specifically how they "mirror" each other in the alphabet.

We will break down the problem, explain how to approach it step-by-step, and then provide a clean and efficient solution in C++. By the end, you should have a good understanding of the problem and the optimal way to solve it.


Problem Statement

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'
  • The mirror of 'b' is 'y'
  • The mirror of 'c' is 'x'
  • ... and so on.

Your task is to calculate a mirror score of the string by following these steps:

  1. Iterate through the string from left to right.
  2. For each index i, find the closest unmarked index j such that j < i and s[j] is the mirror of s[i].
  3. If such a pair (i, j) is found, mark both indices i and j and add the difference i - j to the score.
  4. If no such pair exists, move to the next index without making any changes.
  5. Finally, return the total score after processing the entire string.

Example Walkthrough

Example 1:

Input: s = "aczzx"

Output: 5

Explanation:

  • At i = 0, no matching mirror character exists to the left.
  • At i = 1, no matching mirror character exists to the left.
  • At i = 2, the closest unmarked character to the left is s[0] = 'a', which is the mirror of s[2] = 'z'. We mark both indices and add 2 - 0 = 2 to the score.
  • At i = 3, no matching mirror character exists to the left.
  • At i = 4, the closest unmarked character to the left is s[1] = 'c', which is the mirror of s[4] = 'x'. We mark both indices and add 4 - 1 = 3 to the score.

Thus, the final score is 2 + 3 = 5.

Example 2:

Input: s = "abcdef"

Output: 0

Explanation:

In this case, no pairs of characters match the mirror condition. Therefore, the total score remains 0.


Problem Constraints

  • 1 <= s.length <= 10^5
  • The string s consists only of lowercase English letters.

These constraints imply that we need an efficient solution with a time complexity of O(n)O(n) or O(nlogn)O(n \log n), where nn is the length of the string. We must ensure our solution scales well with larger inputs.


Solution Approach

To solve this problem efficiently, we need to track pairs of mirror characters as we iterate through the string. Here’s a breakdown of the approach:

  1. Mirror Calculation: For each character ch, its mirror is calculated as:

    mirror(ch)=z(cha)\text{mirror(ch)} = 'z' - (ch - 'a')

    This formula ensures that 'a' maps to 'z', 'b' maps to 'y', and so on.

  2. Track Indices: We need to find pairs of characters such that s[i] and s[j] are mirrors of each other. To do this efficiently, we maintain a map (charIndices) that stores the indices of characters we've seen so far. For each character at index i, we check if its mirror exists in the map. If it does, we calculate the score as i - j, mark both indices, and move on.

  3. Efficiency Considerations: By using a hash map to store indices and a boolean array to track marked indices, we avoid nested loops that would result in a time complexity of O(n2)O(n^2). Instead, we achieve a time complexity of O(n)O(n).


C++ Code Implementation

Here's the efficient solution in C++ for finding the mirror score of a string:

#include <vector>
#include <unordered_map>
#include <string>
using namespace std;

class Solution
{
public:
    char getMirrorChar(char ch)
    {
        return 'z' - (ch - 'a');
    }

    long long calculateScore(string s)
    {
        int n = s.size();
        vector<bool> isMarked(n, false);
        unordered_map<char, vector<int>> charIndices;
        long long score = 0;

        for (int i = 0; i < n; ++i)
        {
            char mirrorChar = getMirrorChar(s[i]);
            if (charIndices[mirrorChar].empty())
            {
                charIndices[s[i]].push_back(i);
            }
            else
            {
                int j = charIndices[mirrorChar].back();
                charIndices[mirrorChar].pop_back();
                isMarked[i] = true;
                isMarked[j] = true;
                score += i - j;
            }
        }

        return score;
    }
};


Key Points of the Code

  • getMirrorChar: This function calculates the mirror character for a given character ch by using the formula mirror(ch) = 'z' - (ch - 'a').
  • calculateScore: This is the main function where we iterate over the string, calculate mirrors, and compute the total score based on valid pairs of mirror characters.

Time Complexity

  • Time Complexity: O(n)O(n), where nn is the length of the string. We iterate through the string once and perform constant-time operations (hash map lookups and updates).
  • Space Complexity: O(n)O(n), due to the space required for the charIndices map and the isMarked vector.

Tags

  • LeetCode Problem
  • String Manipulation
  • Mirror Score
  • C++ Solutions
  • Competitive Programming
  • Algorithm Explanation
  • LeetCode Medium
  • Problem Solving

Popular posts from this blog

Maximum Difference Between Even and Odd Frequency | LeetCode

We are given a string consisting of lowercase English letters. Our task is to find the maximum difference between the frequency of two characters in the string such that: One of the characters has an even frequency . The other character has an odd frequency . The difference is calculated as:  odd_frequency - even_frequency We need to return the maximum possible difference between the odd and even frequencies. Example Walkthrough Let's take a couple of examples to better understand the problem: Example 1: Input:  s = "aaaaabbc" Frequencies: 'a' → 5 (odd) 'b' → 2 (even) 'c' → 1 (odd) Here, the maximum odd frequency is 5 (for 'a') and the maximum even frequency is 2 (for 'b'). Therefore, the result is: maxOdd - maxEven = 5 - 2 = 3 Example 2: Input:  s = "abcabcab" Frequencies: 'a' → 3 (odd) 'b' → 2 (even) 'c' → 2 (even) The maximum odd frequency is 3 (for 'a') and the maximum even fr...

Top 10 Beginner-Friendly LeetCode Questions and Their Solutions

If you're new to solving coding problems on LeetCode, it can feel overwhelming. Where do you start? Which problems are suitable for beginners? Don’t worry! In this blog post, I’ll guide you through   10 beginner-friendly LeetCode questions   that are perfect for getting started on your coding journey. These problems will help you build confidence, improve your problem-solving skills, and lay a solid foundation in data structures and algorithms. Why Start with Beginner-Friendly Problems? Before diving into advanced topics like dynamic programming or graph theory, it’s essential to: Build a strong foundation in basic programming concepts. Understand how to approach a coding problem methodically. Gain familiarity with LeetCode’s platform and its problem structure. The following problems are simple yet impactful, designed to introduce you to common techniques like loops, arrays, strings, and basic math operations. 10 Beginner-Friendly LeetCode Problems 1.  Two Sum (Easy) Prob...

Maximize Amount After Two Days of Conversions | Leetcode Question

When tackling the problem of maximizing the amount of currency after two days of conversions, we encounter an interesting graph-based problem that involves working with exchange rates between various currencies. In this article, we will explore this problem in detail, starting with the brute force approach and refining it to an optimized solution. Problem Explanation You are given a string initialCurrency (the starting currency), along with four arrays: pairs1 and rates1 : Represent exchange rates between currency pairs on Day 1. pairs2 and rates2 : Represent exchange rates between currency pairs on Day 2. The task is to maximize the amount of initialCurrency you can have after performing any number of conversions on both days. You can make conversions using Day 1 rates and then further conversions using Day 2 rates. Key Insights: Conversion rates are valid (no contradictions). Each currency can be converted back to its counterpart at a reciprocal rate (e.g., if USD -> EUR = 2....