Check given string is oddly palindrome or not | Set 2
Last Updated :
29 May, 2021
Given string str, the task is to check if characters at the odd indexes of str form a palindrome string or not. If not then print "No" else print "Yes".
Examples:
Input: str = "osafdfgsg", N = 9
Output: Yes
Explanation:
Odd indexed characters are = { s, f, f, s }
so it will make palindromic string, "sffs".
Input: str = "addwfefwkll", N = 11
Output: No
Explanation:
Odd indexed characters are = {d, w, e, w, l}
so it will not make palindrome string, "dwewl"
Naive Approach: Please refer the Set 1 of this article for naive approach
Efficient Approach: The idea is to check if oddString formed by appending odd indices of given string forms a palindrome or not. So, instead of creating oddString and then checking for the palindrome, we can use a stack to optimize running time. Below are the steps:
- For checking oddString to be a palindrome, we need to compare odd indices characters of the first half of the string with odd characters of the second half of string.
- Push odd index character of the first half of the string- into a stack.
- To compare odd index character of the second half with the first half do the following:
- Pop characters from the stack and match it with the next odd index character of the second half of string.
- If the above two characters are not equal then string formed by odd indices is not palindromic. Print "NO" and break from the loop.
- Else match for every remaining odd character of the second half of the string.
- In the end, we need to check if the size of the stack is zero. If it is, then string formed by odd indices will be palindrome, else not.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if string formed
// by odd indices is palindromic or not
bool isOddStringPalindrome(
string str, int n)
{
int oddStringSize = n / 2;
// Check if length of OddString
// odd, to consider edge case
bool lengthOdd
= ((oddStringSize % 2 == 1)
? true
: false);
stack<char> s;
int i = 1;
int c = 0;
// Push odd index character of
// first half of str in stack
while (i < n
&& c < oddStringSize / 2) {
s.push(str[i]);
i += 2;
c++;
}
// Middle element of odd length
// palindromic string is not
// compared
if (lengthOdd)
i = i + 2;
while (i < n && s.size() > 0) {
if (s.top() == str[i])
s.pop();
else
break;
i = i + 2;
}
// If stack is empty
// then return true
if (s.size() == 0)
return true;
return false;
}
// Driver Code
int main()
{
int N = 10;
// Given string
string s = "aeafacafae";
if (isOddStringPalindrome(s, N))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to check if String formed
// by odd indices is palindromic or not
static boolean isOddStringPalindrome(String str,
int n)
{
int oddStringSize = n / 2;
// Check if length of OddString
// odd, to consider edge case
boolean lengthOdd = ((oddStringSize % 2 == 1) ?
true : false);
Stack<Character> s = new Stack<Character>();
int i = 1;
int c = 0;
// Push odd index character of
// first half of str in stack
while (i < n && c < oddStringSize / 2)
{
s.add(str.charAt(i));
i += 2;
c++;
}
// Middle element of odd length
// palindromic String is not
// compared
if (lengthOdd)
i = i + 2;
while (i < n && s.size() > 0)
{
if (s.peek() == str.charAt(i))
s.pop();
else
break;
i = i + 2;
}
// If stack is empty
// then return true
if (s.size() == 0)
return true;
return false;
}
// Driver Code
public static void main(String[] args)
{
int N = 10;
// Given String
String s = "aeafacafae";
if (isOddStringPalindrome(s, N))
System.out.print("Yes\n");
else
System.out.print("No\n");
}
}
// This code is contributed by Rohit_ranjan
Python3
# Python3 program for the above approach
# Function to check if string formed
# by odd indices is palindromic or not
def isOddStringPalindrome(str, n):
oddStringSize = n // 2;
# Check if length of OddString
# odd, to consider edge case
lengthOdd = True if (oddStringSize % 2 == 1) else False
s = []
i = 1
c = 0
# Push odd index character of
# first half of str in stack
while (i < n and c < oddStringSize // 2):
s.append(str[i])
i += 2
c += 1
# Middle element of odd length
# palindromic string is not
# compared
if (lengthOdd):
i = i + 2
while (i < n and len(s) > 0):
if (s[len(s) - 1] == str[i]):
s.pop()
else:
break
i = i + 2
# If stack is empty
# then return true
if (len(s) == 0):
return True
return False;
# Driver code
if __name__=="__main__":
N = 10
# Given string
s = "aeafacafae"
if (isOddStringPalindrome(s, N)):
print("Yes")
else:
print("No")
# This code is contributed by rutvik_56
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to check if String formed
// by odd indices is palindromic or not
static bool isOddStringPalindrome(String str,
int n)
{
int oddStringSize = n / 2;
// Check if length of OddString
// odd, to consider edge case
bool lengthOdd = ((oddStringSize % 2 == 1) ?
true : false);
Stack<char> s = new Stack<char>();
int i = 1;
int c = 0;
// Push odd index character of
// first half of str in stack
while (i < n && c < oddStringSize / 2)
{
s.Push(str[i]);
i += 2;
c++;
}
// Middle element of odd length
// palindromic String is not
// compared
if (lengthOdd)
i = i + 2;
while (i < n && s.Count > 0)
{
if (s.Peek() == str[i])
s.Pop();
else
break;
i = i + 2;
}
// If stack is empty
// then return true
if (s.Count == 0)
return true;
return false;
}
// Driver Code
public static void Main(String[] args)
{
int N = 10;
// Given String
String s = "aeafacafae";
if (isOddStringPalindrome(s, N))
Console.Write("Yes\n");
else
Console.Write("No\n");
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// Javascript program for the above approach
// Function to check if string formed
// by odd indices is palindromic or not
function isOddStringPalindrome( str, n)
{
var oddStringSize = parseInt(n / 2);
// Check if length of OddString
// odd, to consider edge case
var lengthOdd
= ((oddStringSize % 2 == 1)
? true
: false);
var s = [];
var i = 1;
var c = 0;
// Push odd index character of
// first half of str in stack
while (i < n
&& c < parseInt(oddStringSize / 2)) {
s.push(str[i]);
i += 2;
c++;
}
// Middle element of odd length
// palindromic string is not
// compared
if (lengthOdd)
i = i + 2;
while (i < n && s.length > 0) {
if (s[s.length-1] == str[i])
s.pop();
else
break;
i = i + 2;
}
// If stack is empty
// then return true
if (s.length == 0)
return true;
return false;
}
// Driver Code
var N = 10;
// Given string
var s = "aeafacafae";
if (isOddStringPalindrome(s, N))
document.write( "Yes");
else
document.write( "No\n");
// This code is contributed by rrrtnx.
</script>
Time Complexity: O(N)
Space Complexity: O(N)
Efficient Approach 2: The above naive approach can be solved without using extra space. We will use Two Pointers Technique, left and right pointing to first odd index from the beginning and from the end respectively. Below are the steps:
- Check whether length of string is odd or even.
- If length is odd, then initialize left = 1 and right = N-2
- Else, initialize left = 1 and right = N-1
- Increment left pointer by 2 position and decrement right pointer by 2 position.
- Keep comparing the characters pointed by pointers till left <= right.
- If no mis-match occurs then, the string is palindrome, else it is not palindromic.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Functions checks if characters at
// odd index of the string forms
// palindrome or not
bool isOddStringPalindrome(string str,
int n)
{
// Initialise two pointers
int left, right;
if (n % 2 == 0) {
left = 1;
right = n - 1;
}
else {
left = 1;
right = n - 2;
}
// Iterate till left <= right
while (left < n && right >= 0
&& left < right) {
// If there is a mismatch occurs
// then return false
if (str[left] != str[right])
return false;
// Increment and decrement the left
// and right pointer by 2
left += 2;
right -= 2;
}
return true;
}
// Driver Code
int main()
{
int n = 10;
// Given String
string s = "aeafacafae";
// Function Call
if (isOddStringPalindrome(s, n))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Functions checks if characters at
// odd index of the String forms
// palindrome or not
static boolean isOddStringPalindrome(String str,
int n)
{
// Initialise two pointers
int left, right;
if (n % 2 == 0)
{
left = 1;
right = n - 1;
}
else
{
left = 1;
right = n - 2;
}
// Iterate till left <= right
while (left < n && right >= 0 &&
left < right)
{
// If there is a mismatch occurs
// then return false
if (str.charAt(left) !=
str.charAt(right))
return false;
// Increment and decrement the left
// and right pointer by 2
left += 2;
right -= 2;
}
return true;
}
// Driver Code
public static void main(String[] args)
{
int n = 10;
// Given String
String s = "aeafacafae";
// Function Call
if (isOddStringPalindrome(s, n))
System.out.print("Yes\n");
else
System.out.print("No\n");
}
}
// This code is contributed by Rohit_ranjan
Python3
# Python3 program for the above approach
# Functions checks if characters at
# odd index of the string forms
# palindrome or not
def isOddStringPalindrome(Str, n):
# Initialise two pointers
left, right = 0, 0
if (n % 2 == 0):
left = 1
right = n - 1
else:
left = 1
right = n - 2
# Iterate till left <= right
while (left < n and right >= 0 and
left < right):
# If there is a mismatch occurs
# then return false
if (Str[left] != Str[right]):
return False
# Increment and decrement the left
# and right pointer by 2
left += 2
right -= 2
return True
# Driver Code
if __name__ == '__main__':
n = 10
# Given string
Str = "aeafacafae"
# Function call
if (isOddStringPalindrome(Str, n)):
print("Yes")
else:
print("No")
# This code is contributed by himanshu77
C#
// C# program for the above approach
using System;
class GFG{
// Functions checks if characters at
// odd index of the String forms
// palindrome or not
static bool isOddStringPalindrome(String str,
int n)
{
// Initialise two pointers
int left, right;
if (n % 2 == 0)
{
left = 1;
right = n - 1;
}
else
{
left = 1;
right = n - 2;
}
// Iterate till left <= right
while (left < n && right >= 0 &&
left < right)
{
// If there is a mismatch occurs
// then return false
if (str[left] !=
str[right])
return false;
// Increment and decrement the left
// and right pointer by 2
left += 2;
right -= 2;
}
return true;
}
// Driver Code
public static void Main(String[] args)
{
int n = 10;
// Given String
String s = "aeafacafae";
// Function Call
if (isOddStringPalindrome(s, n))
Console.Write("Yes\n");
else
Console.Write("No\n");
}
}
// This code is contributed by Rohit_ranjan
JavaScript
<script>
// Javascript program for the above approach
// Functions checks if characters at
// odd index of the string forms
// palindrome or not
function isOddStringPalindrome(str, n)
{
// Initialise two pointers
var left, right;
if (n % 2 == 0) {
left = 1;
right = n - 1;
}
else {
left = 1;
right = n - 2;
}
// Iterate till left <= right
while (left < n && right >= 0
&& left < right) {
// If there is a mismatch occurs
// then return false
if (str[left] != str[right])
return false;
// Increment and decrement the left
// and right pointer by 2
left += 2;
right -= 2;
}
return true;
}
// Driver Code
var n = 10;
// Given String
var s = "aeafacafae";
// Function Call
if (isOddStringPalindrome(s, n))
document.write( "Yes");
else
document.write( "No");
// This code is contributed by importantly.
</script>
Time Complexity: O(N)
Space Complexity: O(1)
Similar Reads
Check given string is oddly palindrome or not
Given string str, the task is to check if characters at the odd indexes of str form a palindrome string or not. If not then print "No" else print "Yes".Examples: Input: str = "osafdfgsg", N = 9 Output: Yes Explanation: Odd indexed characters are = { s, f, f, s } so it will make palindromic string, "
6 min read
Check if a given string is Even-Odd Palindrome or not
Given a string str, the task is to check if the given string is Even-Odd Palindrome or not. An Even-Odd Palindrome string is defined to be a string whose characters at even indices form a Palindrome while the characters at odd indices also form a Palindrome separately. Examples: Input: str="abzzab"
7 min read
Find if string is K-Palindrome or not | Set 2
Given a string, find out if the string is K-Palindrome or not. A K-palindrome string transforms into a palindrome on removing at most k characters from it.Examples: Input : String - abcdecba, k = 1 Output : Yes String can become palindrome by removing 1 character i.e. either d or e Input : String -
8 min read
Check if given String is Pangram or not
Given a string s, the task is to check if it is Pangram or not. A pangram is a sentence containing all letters of the English Alphabet.Examples: Input: s = "The quick brown fox jumps over the lazy dog" Output: trueExplanation: The input string contains all characters from âaâ to âzâ.Input: s = "The
6 min read
Find if string is K-Palindrome or not | Set 1
Given a string S, find out if the string is K-Palindrome or not. A K-palindrome string transforms into a palindrome on removing at most K characters from it.Examples : Input: S = "abcdecba", k = 1Output: YesExplanation: String can become palindrome by removing 1 character i.e. either d or e. Input:
15+ min read
Check if any anagram of a string is palindrome or not
Given an anagram string S of length N, the task is to check whether it can be made palindrome or not. Examples: Input : S = geeksforgeeks Output: NoExplanation: There is no palindrome anagram of given string Input: S = geeksgeeksOutput: YesExplanation: There are palindrome anagrams of given string.
8 min read
Check if both halves of a string are Palindrome or not
Given a string str, the task is to check whether the given string can be split into two halves, each of which is palindromic. If it is possible, print Yes. Otherwise, print No. Examples: Input: str = "naan" Output: No Explanation: Since both halves "na" and "an" are not palindrome. Input: momdad Out
5 min read
Check if a given string is a rotation of a palindrome
Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
15+ min read
Check if the Sum of Digits is Palindrome or not
Given an integer n, the task is to check whether the sum of digits of n is palindrome or not.Example: Input: n = 56 Output: trueExplanation: Digit sum is (5 + 6) = 11, which is a palindrome.Input: n = 51241 Output: falseExplanation: Digit sum is (5 + 1 + 2 + 4 + 1) = 13, which is not a palindrome.Ta
9 min read
Queries to check if substring[L...R] is palindrome or not
Given a string str and Q queries. Every query consists of two numbers L and R. The task is to print if the sub-string[L...R] is palindrome or not. Examples: Input: str = "abacccde", Q[][] = {{0, 2}, {1, 2}, {2, 4}, {3, 5}} Output: Yes No No Yes Input: str = "abaaab", Q[][] = {{0, 1}, {1, 5}} Output:
12 min read