Given a stream of characters (characters are received one by one), write a function that prints ‘Yes’ if a character makes the complete string palindrome, else prints ‘No’.
Examples:
Input: str[] = "abcba"
Output: a Yes // "a" is palindrome
b No // "ab" is not palindrome
c No // "abc" is not palindrome
b No // "abcb" is not palindrome
a Yes // "abcba" is palindrome
Input: str[] = "aabaacaabaa"
Output: a Yes // "a" is palindrome
a Yes // "aa" is palindrome
b No // "aab" is not palindrome
a No // "aaba" is not palindrome
a Yes // "aabaa" is palindrome
c No // "aabaac" is not palindrome
a No // "aabaaca" is not palindrome
a No // "aabaacaa" is not palindrome
b No // "aabaacaab" is not palindrome
a No // "aabaacaaba" is not palindrome
a Yes // "aabaacaabaa" is palindrome
Let input string be str[0..n-1].
A Simple Solution is to do following for every character str[i] in input string. Check if substring str[0…i] is palindrome, then print yes, else print no.
A Better Solution is to use the idea of Rolling Hash used in Rabin Karp algorithm. The idea is to keep track of reverse of first half and second half (we also use first half and reverse of second half) for every index. Below is complete algorithm.
1) The first character is always a palindrome, so print yes for
first character.
2) Initialize reverse of first half as "a" and second half as "b".
Let the hash value of first half reverse be 'firstr' and that of
second half be 'second'.
3) Iterate through string starting from second character, do following
for every character str[i], i.e., i varies from 1 to n-1.
a) If 'firstr' and 'second' are same, then character by character
check the substring ending with current character and print
"Yes" if palindrome.
Note that if hash values match, then strings need not be same.
For example, hash values of "ab" and "ba" are same, but strings
are different. That is why we check complete string after hash.
b) Update 'firstr' and 'second' for next iteration.
If 'i' is even, then add next character to the beginning of
'firstr' and end of second half and update
hash values.
If 'i' is odd, then keep 'firstr' as it is, remove leading
character from second and append a next
character at end.
Let us see all steps for example
string “abcba” Initial values of ‘firstr’ and ‘second’
firstr’ = hash(“a”), ‘second’ = hash(“b”) Start from second character, i.e., i = 1
- Compare ‘firstr’ and ‘second’, they don’t match, so print no.
- Calculate hash values for next iteration, i.e., i = 2
Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“c”) i = 2
- Compare ‘firstr’ and ‘second’, they don’t match, so print no.
- Calculate hash values for next iteration, i.e., i = 3
Since i is even, ‘firstr’ becomes hash(“ba”) and ‘second’ becomes hash(“cb”) i = 3
- Compare ‘first’ and ‘second’, they don’t match, so print no.
- Calculate hash values for next iteration, i.e., i = 4
Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“ba”) i = 4
- ‘firstr’ and ‘second’ match, compare the whole strings, they match, so print yes
- We don’t need to calculate next hash values as this is last index The idea of using rolling hashes is, next hash value can be calculated from previous in O(1) time by just doing some constant number of arithmetic operations. Below are the implementations of above approach.
C++
#include<bits/stdc++.h>
using namespace std;
#define d 256
#define q 103
void checkPalindromes(string str)
{
int N = str.size();
cout << str[0] << " Yes" << endl;
if (N == 1) return ;
int firstr = str[0] % q;
int second = str[1] % q;
int h = 1, i, j;
for (i=1; i<N; i++)
{
if (firstr == second)
{
for (j = 0; j < i/2; j++)
{
if (str[j] != str[i-j])
break ;
}
(j == i/2)? cout << str[i] << " Yes" << endl: cout << str[i] << " No" << endl;
}
else cout << str[i] << " No" << endl;
if (i != N-1)
{
if (i%2 == 0)
{
h = (h*d) % q;
firstr = (firstr + h*str[i/2])%q;
second = (second*d + str[i+1])%q;
}
else
{
second = (d*(second + q - str[(i+1)/2]*h)%q
+ str[i+1])%q;
}
}
}
}
int main()
{
string txt = "aabaacaabaa" ;
checkPalindromes(txt);
return 0;
}
|
C
#include<stdio.h>
#include<string.h>
#define d 256
#define q 103
void checkPalindromes( char str[])
{
int N = strlen (str);
printf ( "%c Yes\n" , str[0]);
if (N == 1) return ;
int firstr = str[0] % q;
int second = str[1] % q;
int h = 1, i, j;
for (i=1; i<N; i++)
{
if (firstr == second)
{
for (j = 0; j < i/2; j++)
{
if (str[j] != str[i-j])
break ;
}
(j == i/2)? printf ( "%c Yes\n" , str[i]):
printf ( "%c No\n" , str[i]);
}
else printf ( "%c No\n" , str[i]);
if (i != N-1)
{
if (i%2 == 0)
{
h = (h*d) % q;
firstr = (firstr + h*str[i/2])%q;
second = (second*d + str[i+1])%q;
}
else
{
second = (d*(second + q - str[(i+1)/2]*h)%q
+ str[i+1])%q;
}
}
}
}
int main()
{
char *txt = "aabaacaabaa" ;
checkPalindromes(txt);
getchar ();
return 0;
}
|
Java
public class GFG
{
static final int d = 256 ;
static final int q = 103 ;
static void checkPalindromes(String str)
{
int N = str.length();
System.out.println(str.charAt( 0 )+ " Yes" );
if (N == 1 ) return ;
int firstr = str.charAt( 0 ) % q;
int second = str.charAt( 1 ) % q;
int h = 1 , i, j;
for (i = 1 ; i < N; i++)
{
if (firstr == second)
{
for (j = 0 ; j < i/ 2 ; j++)
{
if (str.charAt(j) != str.charAt(i
- j))
break ;
}
System.out.println((j == i/ 2 ) ?
str.charAt(i) + " Yes" : str.charAt(i)+
" No" );
}
else System.out.println(str.charAt(i)+ " No" );
if (i != N - 1 )
{
if (i % 2 == 0 )
{
h = (h * d) % q;
firstr = (firstr + h *str.charAt(i /
2 )) % q;
second = (second * d + str.charAt(i +
1 )) % q;
}
else
{
second = (d * (second + q - str.charAt(
(i + 1 ) / 2 ) * h) % q +
str.charAt(i + 1 )) % q;
}
}
}
}
public static void main(String args[])
{
String txt = "aabaacaabaa" ;
checkPalindromes(txt);
}
}
|
Python
d = 256
q = 103
def checkPalindromes(string):
N = len (string)
print string[ 0 ] + " Yes"
if N = = 1 :
return
firstr = ord (string[ 0 ]) % q
second = ord (string[ 1 ]) % q
h = 1
i = 0
j = 0
for i in xrange ( 1 ,N):
if firstr = = second:
for j in xrange ( 0 ,i / 2 ):
if string[j] ! = string[i - j]:
break
j + = 1
if j = = i / 2 :
print string[i] + " Yes"
else :
print string[i] + " No"
else :
print string[i] + " No"
if i ! = N - 1 :
if i % 2 = = 0 :
h = (h * d) % q
firstr = (firstr + h * ord (string[i / 2 ])) % q
second = (second * d + ord (string[i + 1 ])) % q
else :
second = (d * (second + q - ord (string[(i + 1 ) / 2 ]) * h) % q
+ ord (string[i + 1 ])) % q
txt = "aabaacaabaa"
checkPalindromes(txt)
|
C#
using System;
class GFG
{
public const int d = 256;
public const int q = 103;
public static void checkPalindromes( string str)
{
int N = str.Length;
Console.WriteLine(str[0] + " Yes" );
if (N == 1)
{
return ;
}
int firstr = str[0] % q;
int second = str[1] % q;
int h = 1, i, j;
for (i = 1; i < N; i++)
{
if (firstr == second)
{
for (j = 0; j < i / 2; j++)
{
if (str[j] != str[i - j])
{
break ;
}
}
Console.WriteLine((j == i / 2) ? str[i] +
" Yes" : str[i] + " No" );
}
else
{
Console.WriteLine(str[i] + " No" );
}
if (i != N - 1)
{
if (i % 2 == 0)
{
h = (h * d) % q;
firstr = (firstr + h * str[i / 2]) % q;
second = (second * d + str[i + 1]) % q;
}
else
{
second = (d * (second + q - str[(i + 1) / 2] *
h) % q + str[i + 1]) % q;
}
}
}
}
public static void Main( string [] args)
{
string txt = "aabaacaabaa" ;
checkPalindromes(txt);
}
}
|
Javascript
<script>
function checkPalindromes(str)
{
var d = 256;
var q = 103
var n = str.length;
document.write(str.charAt(0)+ " Yes" );
document.write( "\n" );
if (n==1)
{
return ;
}
var firstr = str.charAt(0) % q;
var second = str.charAt(1) % q;
var h = 1, i, j;
for ( var i = 1; i < n; i++)
{
if (firstr == second)
{
for (j = 0; j < i/2; j++)
{
if (str.charAt(j) != str.charAt(i
- j))
break ;
}
document.write((j == i/2) ?
str.charAt(i) + " Yes" : str.charAt(i)+
" No" );
document.write( "\n" );
}
else document.write(str.charAt(i)+ " No" );
document.write( "\n" );
if (i != n - 1)
{
if (i % 2 == 0)
{
h = (h * d) % q;
firstr = (firstr + h *str.charAt(i /
2)) % q;
second = (second * d + str.charAt(i +
1)) % q;
}
else
{
second = (d * (second + q - str.charAt(
(i + 1) / 2) * h) % q +
str.charAt(i + 1)) % q;
}
}
}
}
var txt = "aabaacaabaa" ;
checkPalindromes(txt);
</script>
|
Output
a Yes
a Yes
b No
a No
a Yes
c No
a No
a No
b No
a No
a Yes
The worst case time complexity of the above solution remains O(n*n), but in general, it works much better than simple approach as we avoid complete substring comparison most of the time by first comparing hash values.
The worst case occurs for input strings with all same characters like “aaaaaa”.
Space Complexity: O(1)
The algorithm uses a fixed number of variables (which is independent of the size of the input string). Hence, the space complexity of the algorithm is O(1).