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


Suppose we have a string s. This string can contain lowercase characters, other special characters and numbers. We have to check whether only the letters present in the string are palindromic or not. Here one constraint is that there we are not allowed to use extra space to solve this problem.

So, if the input is like s = "ra$5ce58car", then the output will be True, as the letters are forming "racecar" which is palindrome.

To solve this, we will follow these steps −

  • Define a function first_letter_index() . This will take str, left, right
  • index := -1
  • for i in range left to right + 1, do
    • if str[i] is lower case alphabet, then
      • index := i
      • come out from loop
  • return index
  • Define a function last_letter_index() . This will take str, left, right
  • index := -1
  • for i in range left to right - 1, decrease by 1, do
    • if str[i] is lower case alphabet, then
      • index := i
      • come out from loop
    • return index
    • From the main method do the following:
    • left := 0, right := size of str - 1
    • flag := True
    • for i in range 0 to size of str, do
      • left := first_letter_index(str, left, right)
      • right := last_letter_index(str, right, left)
      • if right < 0 or left < 0, then
        • come out from loop
      • if str[left] is same as str[right], then
        • left := left + 1
        • right := right - 1
        • go for next iteration
      • flag := False
        • come out from loop
  • return flag

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def first_letter_index(str, left, right):
   index = -1
   for i in range(left, right + 1):
      if str[i] >= 'a' and str[i] <= 'z' :
         index = i
         break
 
   return index

def last_letter_index(str, left, right):
   index = -1
   for i in range(left, right - 1, -1) :
      if str[i] >= 'a' and str[i] <= 'z':
         index = i
         break
 
   return index

def solve(str):
   left = 0
   right = len(str) - 1
   flag = True
 
   for i in range(len(str)) :
      left = first_letter_index(str, left, right)
      right = last_letter_index(str, right, left)
 
      if right < 0 or left < 0:
         break
      if str[left] == str[right]:
         left += 1
         right -= 1
         continue
 
      flag = False
      break
 
   return flag
 
s = "ra$5ce58car"
print(solve(s))

Input

"ra$5ce58car"

Output

True

Updated on: 15-Jan-2021

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements