LeetCode 3412: Find Mirror Score of a String Solution

Master LeetCode problem 3412 (Find Mirror Score of a String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3412. Find Mirror Score of a String

Problem Explanation

Explanation

To solve this problem, we can iterate through the string from left to right. For each character, we check if there exists a mirror character to its left that is unmarked. If such a character is found, we mark both characters and add the difference in their indices to the score. We keep track of the marked characters to avoid marking them again.

Algorithm:

  1. Initialize a variable score to store the total score.
  2. Initialize a set marked to keep track of marked indices.
  3. Iterate through the string from left to right.
  4. For each character at index i, find the closest unmarked index j such that j < i and s[j] is the mirror of s[i].
  5. If such index j exists, mark both indices i and j, add i - j to the score, and add i and j to the marked set.
  6. Continue to the next character and repeat the process.
  7. Return the score at the end.

Time Complexity: O(n), where n is the length of the input string s. Space Complexity: O(n) for the set marked.

Solution Code

class Solution {
    public int findMirrorScore(String s) {
        int score = 0;
        Set<Integer> marked = new HashSet<>();
        
        for (int i = 0; i < s.length(); i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (!marked.contains(j) && isMirror(s.charAt(i), s.charAt(j))) {
                    score += i - j;
                    marked.add(i);
                    marked.add(j);
                    break;
                }
            }
        }
        
        return score;
    }
    
    private boolean isMirror(char a, char b) {
        return Math.abs(a - b) == 25;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3412 (Find Mirror Score of a String)?

This page provides optimized solutions for LeetCode problem 3412 (Find Mirror Score of a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3412 (Find Mirror Score of a String)?

The time complexity for LeetCode 3412 (Find Mirror Score of a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3412 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3412 in Java, C++, or Python.

Back to LeetCode Solutions