Check given string is oddly palindrome or not | Set 2

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


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 intialize 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

Yes

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

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.