Problem Statement

You’re given a string. You need to determine whether the given string is symmetrical or not.

Example 1: Let str = “abab”.

The given is symmetrical as both halves of the string are the same.

Thus, the output is “Yes, the given string is symmetrical”.

Example 2: Let str = “madam”.

If the length of the string is odd, the middle character of the string is ignored. Therefore, 1st half = “ma” and 2nd half = “am”. The two halves are not the same.

Thus, the output is “No, the given string is not symmetrical”.

Example 3: Let str = “madma”.

1st half = “ma” and 2nd half = “ma”. Both halves of the string are the same.

Thus, the output is “Yes, the given string is symmetrical”.

Algorithm to Determine Whether a Given String Is Symmetrical or Not

You can determine whether a given string is symmetrical or not by following the approach below:

Find the length of the string. Find the midIndex of the string. If the length of the string is even, midIndex = length/2. If the length of the string is odd, midIndex = (length/2) + 1. In this case, the middle character of the string is ignored for comparison. Initialize two pointer variables pointer1 and pointer2. pointer1 will store the index of the first character (0) of the string and pointer2 will store the index of the middle character (midIndex) of the string. Now compare the corresponding characters of both halves of the string using a while loop. Run a while loop until pointer1<midIndex and pointer2<lengthOfString. Compare the corresponding characters at indexes pointer1 and pointer2. If any corresponding character is found dissimilar, return false. And if no corresponding characters are found dissimilar, return true. Also, make sure to increment the value of pointer1 and pointer2 in each iteration.

C++ Program to Determine Whether a Given String Is Symmetrical or Not

Below is the C++ program to determine whether a given string is symmetrical or not:

Output:

Python Program to Determine Whether a Given String Is Symmetrical or Not

Below is the Python program to determine whether a given string is symmetrical or not:

Output:

JavaScript Program to Determine Whether a Given String Is Symmetrical or Not

Below is the JavaScript program to determine whether a given string is symmetrical or not:

Output:

Solve Problems Based on Strings

Strings are one of the most important topics for programming interviews. You must solve some of the famous programming problems based on strings like check if a string is a palindrome, check if two strings are anagrams of each other, find the most frequently occurring character in a string, reverse a string, etc. if you’re looking to be fully prepared.