Skip to content
Related Articles

Related Articles

Improve Article

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: 

  1. 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.
  2. Push odd index character of the first half of the string- into a stack.
  3. 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.
  4. 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>
Output: 
Yes

 

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: 

  1. Check whether length of string is odd or even.
  2. If length is odd, then initialize left = 1 and right = N-2
  3. Else, initialize left = 1 and right = N-1
  4. Increment left pointer by 2 position and decrement right pointer by 2 position.
  5. Keep comparing the characters pointed by pointers till left <= right.
  6. 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>
Output: 
Yes

 

Time Complexity: O(N) 
Space Complexity: O(1)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :