Check if there exists a permutation of given string which doesn’t contain any monotonous substring

Given a string S of lowercase English alphabets, the task is to check if there exists an arrangement of string S such that it doesn’t contain any monotonous substring.

A monotonous substring has the following properties:

  • Length os such substring is 2.
  • Both the characters are consecutive, For example – “ab”, “cd”, “dc”, “zy” etc.

Examples:

Input: S = “abcd”
Output: Yes
Explanation:
String S can be rearranged into “cadb” or “bdac”

Input: string = “aab”
Output: No
Explanation:
Every arrangement of the string contains a monotonous substring.



Approach: The idea is group the characters into two different buckets, where one bucket contains the characters which are at the even places and another bucket contains the characters which are at the odd places. Finally, check for the concatenation point of both the group is not a monotonous substring.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation such that there
// are no monotonous
// string in given string
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to check a string doesn't
// contains a monotonous substring
bool check(string s)
{
    bool ok = true;
  
    // Loop to itrate over the string
    // and check that it doesn't contains
    // the monotonous substring
    for (int i = 0; i + 1 < s.size(); ++i)
        ok &= (abs(s[i] - s[i + 1]) != 1);
    return ok;
}
  
// Function to check that there exist
// a arrangement of string such that
// it doesn't contains monotonous substring
string monotonousString(string s)
{
    string odd = "", even = "";
  
    // Loop to group the characters
    // of the string into two buckets
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] % 2 == 0)
            odd += s[i];
        else
            even += s[i];
    }
  
    // Sorting the two buckets
    sort(odd.begin(), odd.end());
    sort(even.begin(), even.end());
  
    // Condition to check if the
    // concatenation point doesn't
    // contains the monotonous string
    if (check(odd + even))
        return "Yes";
    else if (check(even + odd))
        return "Yes";
    return "No";
}
  
// Driver Code
int main()
{
    string str = "abcd";
    string ans;
    ans = monotonousString(str);
    cout << ans << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation such that there
// are no monotonous
// string in given string
import java.io.*;
import java.util.*;
  
class GFG{
      
// Function to check a string doesn't
// contains a monotonous substring
static boolean check(String s)
{
    boolean ok = true;
  
    // Loop to itrate over the string
    // and check that it doesn't contains
    // the monotonous substring
    for (int i = 0; i + 1 < s.length(); ++i)
        ok &= (Math.abs(s.charAt(i) - 
                        s.charAt(i + 1)) != 1);
    return ok;
}
  
// Function to check that there exist
// a arrangement of string such that
// it doesn't contains monotonous substring
static String monotonousString(String s)
{
    String odd = "", even = "";
  
    // Loop to group the characters
    // of the string into two buckets
    for (int i = 0; i < s.length(); ++i)
    {
        if (s.charAt(i) % 2 == 0)
            odd += s.charAt(i);
        else
            even += s.charAt(i);
    }
  
    // Sorting the two buckets
    char oddArray[] = odd.toCharArray(); 
    Arrays.sort(oddArray); 
    odd = new String(oddArray);
      
    char evenArray[] = even.toCharArray(); 
    Arrays.sort(evenArray); 
    even = new String(evenArray);
      
    // Condition to check if the
    // concatenation point doesn't
    // contains the monotonous string
    if (check(odd + even))
        return "Yes";
    else if (check(even + odd))
        return "Yes";
    return "No";
}
  
// Driver Code
public static void main(String []args)
{
    String str = "abcd";
    String ans;
    ans = monotonousString(str);
    System.out.println( ans);
}
}
  
// This code is contributed by ChitraNayal

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation such that there
# are no monotonous string in given string
  
# Function to check a string doesn't
# contains a monotonous substring
def check(s):
      
    ok = True
  
    # Loop to itrate over the string
    # and check that it doesn't contains
    # the monotonous substring
    for i in range(0, len(s) - 1, 1):
        ok = (ok & (abs(ord(s[i]) - 
                        ord(s[i + 1])) != 1))
    return ok
  
# Function to check that there exist
# a arrangement of string such that
# it doesn't contains monotonous substring
def monotonousString(s):
      
    odd = ""
    even = ""
  
    # Loop to group the characters
    # of the string into two buckets
    for i in range(len(s)):
          
        if (ord(s[i]) % 2 == 0):
            odd += s[i]
        else:
            even += s[i]
  
    # Sorting the two buckets
    odd = list(odd)
    odd.sort(reverse = False)
    odd = str(odd)
      
    even = list(even)
    even.sort(reverse = False)
    even = str(even)
  
    # Condition to check if the
    # concatenation point doesn't
    # contains the monotonous string
    if (check(odd + even)):
        return "Yes"
    elif (check(even + odd)):
        return "Yes"
          
    return "No"
  
# Driver Code
if __name__ == '__main__':
      
    str1 = "abcd"
    ans = monotonousString(str1)
      
    print(ans)
  
# This code is contributed by Samarth

chevron_right


Output:

Yes

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.




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.



Improved By : ipg2016107, chitranayal