Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 <bits/stdc++.h>
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[1] - temp[0];
 
            // 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 Code
int 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 approach
import java.util.*;
class GFG{
 
// Function to check str can be
// rearranged such that characters
// of each word forms an AP
static 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 Code
public 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 AP
def checkWordAP(st):
 
    # Stores each word of
    # the given string
    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[1]) - ord(temp[0])
 
            # 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 Code
if __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 approach
using System;
class GFG{
 
// Function to check str can be
// rearranged such that characters
// of each word forms an AP
static 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[1] - temp[0];
 
      // 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 Code
public 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




<script>
// Javascript program to implement
// the above approach
 
// Function to check str can be
// rearranged such that characters
// of each word forms an AP
function checkWordAP(s)
{
 
    // Stores the String
  // in Stringstream
  let str = s.split(" ");
  
  // Stores each word of
  // the given String
  
  for (let temp = 0; temp < str.length; temp++ )
  {
   
    // Sort the current word
    str[temp] = sort(str[temp]);
  
    // Check if the current word
    // of the given String is in AP
    for (let i = 2; i < str[temp].length; i++)
    {
     
      // Store the value of difference
      // between adjacent characters
      let diff = str[temp][1].charCodeAt(0) - str[temp][0].charCodeAt(0);
  
      // Check if difference between all
      // adjacent characters are equal
      if (diff != str[temp][i].charCodeAt(0) - str[temp][i-1].charCodeAt(0))
      {
        return false;
      }
    }
  }
  
  // If all words are in AP.
  return true;
}
 
function sort(inputString)
{
 
    // convert input string to char array
  let tempArray = inputString.split("");
  
  // sort tempArray
  (tempArray).sort();
  
  // return new sorted string
  return (tempArray).join("");
}
 
// Driver Code
let str = "ace yzx fbd";
  
  // If all words of the given
  // String are in AP
  if (checkWordAP(str))
  {
    document.write("Yes");
  }
  else
  {
    document.write("No");
  }
 
// This code is contributed by patel2127
</script>


Output

Yes

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



Last Updated : 08 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads