Check if characters of each word can be rearranged to form an Arithmetic Progression (AP)

• Last Updated : 21 Jun, 2021

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: true
Explanation: Rearrange the given string to “ace xyz bdf”.
All the characters of the word “ace” are in AP with a common difference of 2.
All the characters of the word “xyz” are in AP with a common difference of 1
All the characters of the word “bdf” are in AP with a common difference of 2.
Therefore, the required output is true.

Input: str = “geeks for geeks”
Output: false

Approach: The idea is to sort each word of the given string and check if the difference between adjacent characters in all the words are equal or not. If found to be true, then print Yes. Otherwise, print No. Follow the steps below to solve the problem.

1. Iterate over string str, and split each word of str by a space delimiter.
2. Sort each word of the given string in ascending order.
3. Check if the difference between all the adjacent characters of the words is equal.
4. If found to be true, print Yes. Otherwise, print No.

Below is the implementation of the above approach:

C++

 // C++ program to implement// the above approach #include using namespace std; // Function to check str can be// rearranged such that characters// of each word forms an AP int checkWordAP(string str){    // Stores the string    // in stringstream    stringstream ss(str);     // Stores each word of    // the given string    string temp;    while (getline(ss, temp, ' ')) {        // Sort the current word        sort(temp.begin(), temp.end());         // Check if the current word        // of the given string is in AP        for (int i = 2; i < temp.length();             i++) {            // Store the value of difference            // between adjacent characters            int diff = temp - temp;             // Check if difference between all            // adjacent characters are equal            if (diff != temp[i] - temp[i - 1]) {                return false;            }        }    }     // If all words are in AP.    return true;} // Driver Codeint main(){    string str = "ace yzx fbd";     // If all words of the given    // string are in AP    if (checkWordAP(str)) {        cout << "Yes";    }    else {        cout << "No";    }}

Java

 // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to check str can be// rearranged such that characters// of each word forms an APstatic boolean checkWordAP(String s){  // Stores the String  // in Stringstream  String str[] = s.split(" ");   // Stores each word of  // the given String   for (String temp : str )  {    // Sort the current word    temp = sort(temp);     // Check if the current word    // of the given String is in AP    for (int i = 2; i < temp.length(); i++)    {      // Store the value of difference      // between adjacent characters      int diff = temp.charAt(1) - temp.charAt(0);       // Check if difference between all      // adjacent characters are equal      if (diff != temp.charAt(i) - temp.charAt(i - 1))      {        return false;      }    }  }   // If all words are in AP.  return true;}   static String sort(String inputString){  // convert input string to char array  char tempArray[] = inputString.toCharArray();   // sort tempArray  Arrays.sort(tempArray);   // return new sorted string  return new String(tempArray);} // Driver Codepublic static void main(String[] args){  String str = "ace yzx fbd";   // If all words of the given  // String are in AP  if (checkWordAP(str))  {    System.out.print("Yes");  }  else  {    System.out.print("No");  }}} // This code is contributed by Princi Singh

Python3

 # Python3 program to implement# the above approach # Function to check st can be# rearranged such that characters# of each word forms an APdef checkWordAP(st):     # Stores each word of    # the given sting    st = st.split(" ")         for temp in st:                 # Sort the current word        temp = sorted(temp)         # Check if the current word        # of the given is in AP        for i in range(2, len(temp)):                         # Store the value of difference            # between adjacent characters            diff = ord(temp) - ord(temp)             # Check if difference between all            # adjacent characters are equal            if (diff != ord(temp[i]) -                        ord(temp[i - 1])):                return False     # If all words are in AP.    return True # Driver Codeif __name__ == '__main__':         st = "ace yzx fbd"     # If all words of the given    # are in AP    if (checkWordAP(st)):        print("Yes")    else:        print("No") # This code is contributed by mohit kumar 29

C#

 // C# program to implement// the above approachusing System;class GFG{ // Function to check str can be// rearranged such that characters// of each word forms an APstatic bool checkWordAP(String s){  // Stores the String  // in Stringstream  String []str = s.Split(' ');   // Stores each word of  // the given String  String temp = "";  foreach (String temp1 in str )  {    // Sort the current word    temp = sort(temp1);     // Check if the current word    // of the given String is in AP    for (int i = 2; i < temp.Length; i++)    {      // Store the value of difference      // between adjacent characters      int diff = temp - temp;       // Check if difference between all      // adjacent characters are equal      if (diff != temp[i] - temp[i - 1])      {        return false;      }    }  }   // If all words are in AP.  return true;}   static String sort(String inputString){  // convert input string to char array  char []tempArray = inputString.ToCharArray();   // sort tempArray  Array.Sort(tempArray);   // return new sorted string  return new String(tempArray);} // Driver Codepublic static void Main(String[] args){  String str = "ace yzx fbd";   // If all words of the given  // String are in AP  if (checkWordAP(str))  {    Console.Write("Yes");  }  else  {    Console.Write("No");  }}} // This code is contributed by Princi Singh

Javascript


Output
Yes

Time Complexity: O(N log2N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up