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: 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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";
    }
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 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[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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output

Yes

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

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

Program Analyst Trainee,Cognizant

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.