Check given string is oddly palindrome or not | Set 2
Last Updated :
15 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem