VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-the-characters-in-a-string-form-a-palindrome-in-o1-extra-space/

⇱ Check if the characters in a string form a Palindrome in O(1) extra space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if the characters in a string form a Palindrome in O(1) extra space

Last Updated : 22 Dec, 2023

Given string str. The string may contain lower-case letters, special characters, digits, or even white spaces. The task is to check whether only the letters present in the string are forming a Palindromic combination or not without using any extra space.

Note: It is not allowed to use extra space to solve this problem. Also, the letters present in the string are in lower-case and the string may contain special characters, digits, or even white spaces along with lowercase letters.

Examples

Input : str = "m a 343 la y a l am" 
Output : YES 
The characters in the string form the sequence "malayalam", which is a palindrome.

Input : str = "malayalam" 
Output : YES

Approach:

  • Create two utility functions to get the first and last position of characters present in the string.
  • Start traversing the string, and keep finding the position of the first and last characters every time.
  • If the first and last characters are the same for every iteration and the string is traversed completely, then print YES, otherwise print NO.

Below is the implementation of the above approach: 


Output
YES

Time complexity: O(N), where N is length of given string
Auxiliary space: O(1)

Comment