Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Group Shifted String

  • Difficulty Level : Medium
  • Last Updated : 23 Jun, 2021

Given an array of strings (all lowercase letters), the task is to group them in such a way that all strings in a group are shifted versions of each other. Two string S and T are called shifted if, 

S.length = T.length 
and
S[i] = T[i] + K for 
1 <= i <= S.length  for a constant integer K

For example strings, {acd, dfg, wyz, yab, mop} are shifted versions of each other.

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input  : str[] = {"acd", "dfg", "wyz", "yab", "mop",
                 "bdfh", "a", "x", "moqs"};

Output : a x
         acd dfg wyz yab mop
         bdfh moqs
All shifted strings are grouped together.

We can see a pattern among the string of one group, the difference between consecutive characters for all character of the string are equal. As in the above example take acd, dfg and mop
a c d -> 2 1 
d f g -> 2 1 
m o p -> 2 1
Since the differences are the same, we can use this to identify strings that belong to the same group. The idea is to form a string of differences as key. If a string with the same difference string is found, then this string also belongs to the same group. For example, the above three strings have the same difference string, which is “21”. 
In the below implementation, we add ‘a’ to every difference and store 21 as “ba”.
 

C++




/* C/C++ program to print groups of shifted strings
   together. */
#include <bits/stdc++.h>
using namespace std;
const int ALPHA = 26;   // Total lowercase letter
 
// Method to a difference string for a given string.
// If string is "adf" then difference string will be
// "cb" (first difference 3 then difference 2)
string getDiffString(string str)
{
    string shift = "";
    for (int i = 1; i < str.length(); i++)
    {
        int dif = str[i] - str[i-1];
        if (dif < 0)
            dif += ALPHA;
 
        // Representing the difference as char
        shift += (dif + 'a');
    }
 
    // This string will be 1 less length than str
    return shift;
}
 
// Method for grouping shifted string
void groupShiftedString(string str[], int n)
{
    // map for storing indices of string which are
    // in same group
    map< string, vector<int> > groupMap;
    for (int i = 0; i < n; i++)
    {
        string diffStr = getDiffString(str[i]);
        groupMap[diffStr].push_back(i);
    }
 
    // iterating through map to print group
    for (auto it=groupMap.begin(); it!=groupMap.end();
                                                it++)
    {
        vector<int> v = it->second;
        for (int i = 0; i < v.size(); i++)
            cout << str[v[i]] << " ";
        cout << endl;
    }
}
 
// Driver method to test above methods
int main()
{
    string str[] = {"acd", "dfg", "wyz", "yab", "mop",
                    "bdfh", "a", "x", "moqs"
                   };
    int n = sizeof(str)/sizeof(str[0]);
    groupShiftedString(str, n);
    return 0;
}

Python3




# Python3 program to print groups
# of shifted strings together.
 
# Total lowercase letter
ALPHA = 26
 
# Method to a difference string
# for a given string. If string
# is "adf" then difference string
# will be "cb" (first difference
# 3 then difference 2)
def getDiffString(str):
   
    shift=""
 
    for i in range(1, len(str)):
        dif = (ord(str[i]) -
              ord(str[i - 1]))
 
        if(dif < 0):
            dif += ALPHA
 
        # Representing the difference
        # as char
        shift += chr(dif + ord('a'))
 
    # This string will be 1 less
    # length than str
    return shift
 
# Method for grouping
# shifted string
def groupShiftedString(str,n):
 
    # map for storing indices
    # of string which are
    # in same group
    groupMap = {}
 
    for i in range(n):
        diffStr = getDiffString(str[i])
        if diffStr not in groupMap:
            groupMap[diffStr] = [i]
        else:
            groupMap[diffStr].append(i)
     
    # Iterating through map
    # to print group
    for it in groupMap:
        v = groupMap[it]
        for i in range(len(v)):
            print(str[v[i]], end = " ")
        print()
         
# Driver code
str = ["acd", "dfg", "wyz",
       "yab", "mop","bdfh",
       "a", "x", "moqs"]
n = len(str)
groupShiftedString(str, n)
 
# This code is contributed by avanitrachhadiya2155

Javascript




<script>
 
/* Javascript program to print groups of shifted strings
   together. */
let ALPHA = 26;
 
// Method to a difference string for a given string.
// If string is "adf" then difference string will be
// "cb" (first difference 3 then difference 2)
function getDiffString(str)
{
    let shift = "";
    for (let i = 1; i < str.length; i++)
    {
        let dif = str[i] - str[i-1];
        if (dif < 0)
            dif += ALPHA;
  
        // Representing the difference as char
        shift += (dif + 'a');
    }
  
    // This string will be 1 less length than str
    return shift;
}
 
// Method for grouping shifted string
function groupShiftedString(str, n)
{
 
    // map for storing indices of string which are
    // in same group
    let groupMap = new Map();
    for (let i = 0; i < n; i++)
    {
        let diffStr = getDiffString(str[i]);
        if(!groupMap.has(diffStr))
            groupMap.set(diffStr,[]);   
        groupMap.get(diffStr).push(i);
    }
  
    // iterating through map to print group
    for (let [key, value] of groupMap.entries())
    {
        let v = value;
        for (let i = 0; i < v.length; i++)
            document.write(str[v[i]]+" ");
        document.write("<br>")
    }
}
 
// Driver method to test above methods
let str=["acd", "dfg", "wyz", "yab", "mop",
                    "bdfh", "a", "x", "moqs"];
let n = str.length;
groupShiftedString(str, n);
 
// This code is contributed by ab2127
</script>

Output: 
 

a x
acd dfg wyz yab mop
bdfh moqs

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :