Check if the given string is the same as its reflection in a mirror

Given a string S containing only uppercase English characters. The task is to find whether S is the same as its reflection in a mirror.

Examples:

Input: str = "AMA"
Output: YES
AMA is same as its reflection in the mirror.

Input: str = "ZXZ"
Output: NO

Approach: The string obviously has to be a palindrome, but that alone is not enough. All characters in the string should be symmetric so that their reflection is also the same. The symmetric characters are AHIMOTUVWXY.

  • Store the symmetric characters in an unordered_set.
  • Traverse the string and check if there is any non-symmetric character present in the string. If yes then return false.
  • Else check if the string is palindrome or not. If the string is palindrome also then return true else return false.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the 
// above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to check reflection
bool isReflectionEqual(string s)
{
    // Symmetric characters
    unordered_set<char> symmetric = { 'A', 'H', 'I', 'M',
                        'O', 'T', 'U', 'V', 'W', 'X', 'Y' };
  
    int n = s.length();
  
    for (int i = 0; i < n; i++)
        // If any non-symmetric character is
        // present, the answer is NO
        if (symmetric.find(s[i]) == symmetric.end())
            return false;
  
    string rev = s;
    reverse(rev.begin(), rev.end());
  
    // Check if the string is a palindrome
    if (rev == s)
        return true;
    else
        return false;
}
  
// Driver code
int main()
{
    string s = "MYTYM";
    if (isReflectionEqual(s))
        cout << "YES";
    else
        cout << "NO";
}

chevron_right


Output:

YES

Time Complexity: O(N)



My Personal Notes arrow_drop_up