Skip to content
Related Articles

Related Articles

Improve Article

Check whether it is possible to permute string such that it does not contain a palindrome of length 2

  • Last Updated : 10 May, 2021
Geek Week

Given a strings S length N consisting of only ‘a’, ‘b’ and ‘c’. The task is to check if it is possible to permute the characters of S such that it will not contain a palindrome of length 2 or more as a substring.

Examples:

Input: S = "abac"
Output: Yes
Explanation : 
1. The string contains a palindrome "aba". 
2. We can permute the last three characters as follows: S = "acba". 
3. Therefore, it does not contain any palindrome of length 2 or more. 

Input: S = "aba"
Output: No

Approach: Follow the below steps to solve the problem:

  • Traverse through the string.
  • For a palindrome of length 2, both the characters should be same- i.e. “aa” or “bb” or “cc”.
  • Similarly, for a palindrome of length 3, same letters are separated by another letter. Example – “a ? a” , “b ? b”.
  • Therefore, any two same characters must be separated by at least two characters.
  • Find the frequency of characters of the string.
  • If the difference of count of :
    • “a” and “b” is less than 1
    • “b” and “c” is less than 1
    • “a” and “c” is less than 1
  • If all the three conditions are true, return “Yes”
  • Else return “No”.

Below is the implementation of the above approach:

C++




// C++ implementation to print the character and
// its frequency in order of its occurrence
#include <bits/stdc++.h>
using namespace std;
 
void isPossible(string &str)
{
     
    //Find the frequency of the characters
    //in the string
    map<char, int> mp;
    for(auto it : str){
        mp[it]++;
    }
     
    //Count of characters
    int x = mp['a'];
    int y = mp['b'];
    int z = mp['c'];
     
    //If satisfies the conditions
    if(abs(x-y) <= 1 and abs(y-z) <= 1 and abs(x-z) <= 1){
        cout << "Yes" << "\n";
    }
    //Return No
    else{
        cout << "No" << "\n";
    }
}
 
// Driver program to test above
int main()
{
    string str = "abac";
     
    isPossible(str);
     
    return 0;
}

Java




// Java implementation to print the
// character and its frequency in
// order of its occurrence
import java.io.*;
import java.util.*;
 
class GFG{
     
public static void isPossible(String str)
{
     
    // Find the frequency of the characters
    // in the string
    HashMap<Character,
            Integer> mp = new HashMap<Character,
                                      Integer>();
    for(int i = 0; i < str.length(); i++)
    {
        if (mp.containsKey(str.charAt(i)))
        {
            mp.put(str.charAt(i),
            mp.get(str.charAt(i)) + 1);
        }
        else
        {
            mp.put(str.charAt(i), 1);
        }
    }
     
    // Count of characters
    int x = mp.get('a');
    int y = mp.get('b');
    int z = mp.get('c');
      
    // If satisfies the conditions
    if (Math.abs(x - y)<= 1 &&
        Math.abs(y - z) <= 1 &&
        Math.abs(x - z) <= 1)
    {
        System.out.println("Yes");
    }
     
    // Return No
    else
    {
        System.out.println("No");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "abac";
     
    isPossible(str);
}
}
 
// This code is contributed by rag2127

Python3




# Python3 implementation to print the character and
# its frequency in order of its occurrence
def isPossible(Str) :
     
    # Find the frequency of the characters
    # in the string
    mp = {}
    for it in Str :
        if it in mp :
            mp[it] += 1
        else :
            mp[it] = 1
     
    # Count of characters
    x = mp['a']
    y = mp['b']
    z = mp['c']
     
    # If satisfies the conditions
    if(abs(x - y) <= 1 and abs(y - z) <= 1 and abs(x - z) <= 1) :
        print("Yes")
     
    # Return No
    else :
        print("No")
 
# Driver code
Str = "abac"
 
isPossible(Str)
 
# This code is contributed by divyesh072019

C#




// C# implementation to print the
// character and its frequency in
// order of its occurrence
using System;
using System.Collections.Generic;
 
class GFG{
     
static void isPossible(string str)
{
     
    // Find the frequency of the characters
    // in the string
    Dictionary<char,
               int> mp = new Dictionary<char,
                                        int>();
                                         
    foreach(char it in str)
    {
        if (mp.ContainsKey(it))
        {
            mp[it]++;
        }
        else
        {
            mp[it] = 1;
        }
    }
     
    // Count of characters
    int x = mp['a'];
    int y = mp['b'];
    int z = mp['c'];
      
    // If satisfies the conditions
    if (Math.Abs(x - y) <= 1 &&
        Math.Abs(y - z) <= 1 &&
        Math.Abs(x - z) <= 1)
    {
        Console.WriteLine("Yes");
    }
     
    // Return No
    else
    {
        Console.WriteLine("No");
    }
}
 
// Driver Code
static void Main()
{
    string str = "abac";
     
    isPossible(str);
}
}
 
// This code is contributed by divyeshrabadiya07

Javascript




<script>
 
// Javascript implementation to
// print the character and
// its frequency in order of
// its occurrence
 
function isPossible(str)
{
     
    // Find the frequency of the characters
    // in the string
    var mp = new Map();
 
    for(var i = 0; i<str.length; i++)
    {
        var it = str[i];
         
        if(mp.has(it))
        {
            mp.set(it, mp.get(it)+1);
        }
        else
        {
            mp.set(it, 1);
        }
    }
     
    //Count of characters
    var x = mp.get('a');
    var y = mp.get('b');
    var z = mp.get('c');
     
    //If satisfies the conditions
    if(Math.abs(x-y) <= 1 && Math.abs(y-z) <=
    1 && Math.abs(x-z) <= 1){
        document.write( "Yes" + "<br>");
    }
    // Return No
    else{
        document.write( "No" + "<br>");
    }
}
 
// Driver program to test above
 
var str = "abac";
isPossible(str);
 
 
</script>

Output:

Yes

Time Complexity : O(N), where N is the length of the string

Space Complexity: O(N)

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :