Open In App

Check if string can be rearranged so that every Odd length Substring is Palindrome

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S. The task is to check whether it is possible to rearrange the string such that every substring of odd length is a palindrome.

Examples: 

Input: S = "oiooi" 
Output: YES 
The string can be rearranged as "oioio"
Input: S = "yuyuo" 
Output: NO 

Approach:  

  • The very first observation is if all the characters of the string are the same then every substring of odd length is a palindrome, and we do not need to rearrange them.
  • The second observation is if the number of distinct characters is more than 2 then it is impossible to rearrange.
  • Now if the number of distinct characters are exactly 2 then to get all odd length substring to be a palindrome, the difference of their count must be less than or equal to 1, and if this satisfies then we rearrange the string in an alternate manner means

s_{i-1}=s_{i+1}

  • for i <— ( 1 to n – 1 ). Where n is the length of the string.


Below is the implementation of the above approach: 
 

C++

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check is it
// possible to rearrange the string
// such that every odd length
// substring is palindrome
bool IsPossible(string s)
{
 
    // Length of the string
    int n = s.length();
 
    // To count number of distinct
    // character in string
    set<char> count;
 
    // To count frequency of
    // each character
    map<char, int> map;
 
    for (int i = 0; i < n; i++) {
 
        // Inserting into set
        count.insert(s[i]);
 
        // Incrementing the frequency
        map[s[i]] += 1;
    }
 
    // All characters in
    // the string are same
    if (count.size() == 1) {
        return true;
    }
 
    // There are more than 2 different
    // character in string
    if (count.size() > 2) {
        return false;
    }
 
    // Currently there is 2 different
    // character in string
    auto it = count.begin();
 
    // Get the frequencies of the
    // characters that present
    // in string
    int x = 0, y = 0;
    x = map[*it];
 
    it++;
    y = map[*it];
 
    // Difference between their
    // count is less than or
    // equal to 1
    if (abs(x - y) <= 1) {
        return true;
    }
 
    return false;
}
 
// Driver code
int main()
{
    string s = "aaaddad";
 
    if (IsPossible(s))
        cout << "YES\n";
    else
        cout << "NO\n";
 
    return 0;
}

                    

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    // Function to check is it
    // possible to rearrange the string
    // such that every odd length
    // substring is palindrome
    static boolean IsPossible(String s)
    {
 
        // Length of the string
        int n = s.length();
 
        // To count number of distinct
        // character in string
        HashSet<Character> count = new HashSet<>();
 
        // To count frequency of
        // each character
        HashMap<Character, Integer> map = new HashMap<>();
 
        for (int i = 0; i < n; i++)
        {
 
            // Inserting into set
            count.add(s.charAt(i));
 
            // Incrementing the frequency
            map.put(s.charAt(i), map.get(s.charAt(i)) ==
                    null ? 1 : map.get(s.charAt(i)) + 1);
        }
 
        // All characters in
        // the string are same
        if (count.size() == 1)
            return true;
 
        // There are more than 2 different
        // character in string
        if (count.size() > 2)
            return false;
 
        String newString = count.toArray().toString();
 
        // Currently there is 2 different
        // character in string
        int j = 0;
        char it = newString.charAt(j);
 
        // Get the frequencies of the
        // characters that present
        // in string
        int x = 0, y = 0;
        x = map.get(it) == null ? 0 : map.get(it);
        j++;
 
        it = newString.charAt(j);
        y = map.get(it) == null ? 0 : map.get(it);
 
        // Difference between their
        // count is less than or
        // equal to 1
        if (Math.abs(x - y) <= 1)
            return true;
        return false;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "aaaddad";
        if (IsPossible(s))
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}
 
// This code is contributed by
// sanjeev2552

                    

Python3

# Python3 implementation of
# the above approach
 
# Function to check is it
# possible to rearrange the string
# such that every odd length
# substring is palindrome
def IsPossible(s) :
 
    # Length of the string
    n = len(s);
 
    # To count number of distinct
    # character in string
    count = set();
     
    # To count frequency of
    # each character
    map = dict.fromkeys(s, 0);
 
    for i in range(n) :
 
        # Inserting into set
        count.add(s[i]);
 
        # Incrementing the frequency
        map[s[i]] += 1;
 
    # All characters in
    # the string are same
    if (len(count) == 1) :
        return True;
 
    # There are more than 2 different
    # character in string
    if (len(count) > 2) :
        return False;
         
    # Currently there is 2 different
    # character in string
    j = 0
    it = list(count)[j];
 
    # Get the frequencies of the
    # characters that present
    # in string
    x = 0; y = 0;
    x = map[it];
     
    j += 1
    it = list(count)[j];
    y = map[it];
 
    # Difference between their
    # count is less than or
    # equal to 1
    if (abs(x - y) <= 1) :
        return True;
 
    return False;
 
# Driver code
if __name__ == "__main__" :
 
    s = "aaaddad";
 
    if (IsPossible(s)) :
        print("YES");
    else :
        print("NO");
         
# This code is contributed by AnkitRai01

                    

C#

// C# implementation of the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to check is it
// possible to rearrange the string
// such that every odd length
// substring is palindrome
static bool IsPossible(String s)
{
 
  // Length of the string
  int n = s.Length;
 
  // To count number of distinct
  // character in string
  HashSet<char> count =
          new HashSet<char>();
 
  // To count frequency of
  // each character
  Dictionary<char,
             int> map = new Dictionary<char,
                                       int>();
 
  for (int i = 0; i < n; i++)
  {
    // Inserting into set
    count.Add(s[i]);
 
    // Incrementing the frequency
    if(map.ContainsKey(s[i]))
      map[s[i]] = map[s[i]] + 1;
    else
      map.Add(s[i], 1);
  }
 
  // All characters in
  // the string are same
  if (count.Count == 1)
    return true;
 
  // There are more than 2 different
  // character in string
  if (count.Count > 2)
    return false;
 
  String newString = count.ToString();
 
  // Currently there is 2 different
  // character in string
  int j = 0;
  char it = newString[j];
 
  // Get the frequencies of the
  // characters that present
  // in string
  int x = 0, y = 0;
  x = !map.ContainsKey(it) ?
       0 : map[it];
  j++;
 
  it = newString[j];
  y = !map.ContainsKey(it) ?
       0 : map[it];
 
  // Difference between their
  // count is less than or
  // equal to 1
  if (Math.Abs(x - y) <= 1)
    return true;
  return false;
}
 
// Driver Code
public static void Main(String[] args)
{
  String s = "aaaddad";
  if (IsPossible(s))
    Console.WriteLine("YES");
  else
    Console.WriteLine("NO");
}
}
 
// This code is contributed by 29AjayKumar

                    

Javascript

function IsPossible(s) {
    // Length of the string
    let n = s.length;
 
    // To count number of distinct
    // character in string
    let count = new Set();
 
    // To count frequency of
    // each character
    let map = new Map();
 
    for (let i = 0; i < n; i++) {
        // Inserting into set
        count.add(s[i]);
 
        // Incrementing the frequency
        if (map.has(s[i])) {
            map.set(s[i], map.get(s[i]) + 1);
        } else {
            map.set(s[i], 1);
        }
    }
 
    // All characters in
    // the string are same
    if (count.size === 1) return true;
 
    // There are more than 2 different
    // character in string
    if (count.size > 2) return false;
 
    let newArray = [...count];
 
    // Currently there is 2 different
    // character in string
    for (let it of newArray) {
        // Get the frequencies of the
        // characters that present
        // in string
        let x = 0, y = 0;
        x = map.get(it) || 0;
 
        // get the other character
        let it2 = newArray.find(c => c !== it);
        y = map.get(it2) || 0;
 
        // Difference between their
        // count is less than or
        // equal to 1
        if (Math.abs(x - y) <= 1) return true;
    }
    return false;
}
 
// Driver Code
let s = "aaaddad";
if (IsPossible(s)) {
    console.log("YES");
} else {
    console.log("NO");
}
// contributed by dany

                    

Output: 
YES

 

Time Complexity: O(n) ,where n is length of given string

Auxiliary Space: O(n)



Similar Reads

Longest substring whose characters can be rearranged to form a Palindrome
Given a string S of length N which only contains lowercase alphabets. Find the length of the longest substring of S such that the characters in it can be rearranged to form a palindrome. Examples: Input: S = “aabe”Output: 3Explanation:The substring “aab” can be rearranged to form "aba", which is a palindromic substring.Since the length of “aab” is
16 min read
Find the number of ways to form a string of length N that can be rearranged to include S as a substring.
Given an integer N and string S of size M, the task is to find the number of ways of forming string of length N such that it is possible to rearrange the string to have S as substring. Print the answer modulo 109 + 7. Note: All characters of string S are distinct. Examples: Input: N = 3, S = "abc"Output: 6Explanation: There are 6 strings that can b
8 min read
Check if a string can be rearranged to form special palindrome
Given a string str, the task is to check if it can be rearranged to get a special palindromic string. If we can make it print YES else print NO. A string is called special Palindrome that contains an uppercase and a lower case character of the same character in the palindrome position. Example: ABCcba is a special palindrome but ABCCBA is not a spe
8 min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram PalindromeTry It! A set of characters can form a pa
14 min read
Minimum removals required such that a string can be rearranged to form a palindrome
Given a string S consisting of lowercase English alphabets, the task is to find the minimum number of characters required to be removed such that the characters of the string could be rearranged to form a palindrome. Examples: Input: S = "ababccca"Output: 1Explanation:Remove the occurrence of 'c' from the string. Therefore, the modified string is "
6 min read
Check if an array arr[] can be rearranged such that arr[2 × i + 1] = 2* arr[2 × i] for every ith index
Given an array arr[] consisting of 2*N integers, the task is to check if it is possible to rearrange the array elements such that arr[2 * i + 1] = 2* arr[2 * i] for every ith index. If it is possible to do so, then print "Yes. Otherwise, print "No". Examples: Input: arr[] = {4, -2, 2, -4}, N = 2Output: YesExplanation: Rearrange the array as arr[] =
8 min read
Find smallest Substring to be rearranged to make String lexicographically sorted
Given a string S, the task is to find out the length of the smallest substring of S that needs to be rearranged so that all the characters of the string S are in lexicographical order. Examples: Input: S = "aabbace"Output: 3Explanation: Rearranging "bba" to be "abb".S becomes "aaabbce" which is in lexicographical order. Input: S = "abez"Output: 0 A
4 min read
Check if given Array can be rearranged as increasing, decreasing or a hill sequence
Given an array arr[] of size N. The task is to find the number of sequences in which any one of the following conditions is met: The given sequence can be re-arranged into strictly increasing order, orThe given sequence can be re-arranged into strictly decreasing order, orThe given sequence can be re-arranged into Hill sequence order. The task is t
10 min read
Check if characters of each word can be rearranged to form an Arithmetic Progression (AP)
Given string str, the task is to check if it is possible to rearrange the string such that the characters of each word of the given string are in Arithmetic Progression. Examples: Input: str = "ace yzx fbd"Output: trueExplanation: Rearrange the given string to "ace xyz bdf".All the characters of the word "ace" are in AP with a common difference of
7 min read
Check if rows of a Matrix can be rearranged to make Bitwise XOR of first column non-zero
Given a matrix mat[][] of size N * M, the task is to check if it is possible to rearrange the row elements of the matrix such that Bitwise XOR of the first column element is non-zero. If it is possible then print "Yes" else print "No". Examples: Input: mat[][] = {{1, 1, 2}, {2, 2, 2}, {3, 3, 3}}Output: YesExplanation:After rearranging the first row
7 min read
Article Tags :
Practice Tags :