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.
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++
#include <bits/stdc++.h>
using namespace std;
const int ALPHA = 26;
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;
shift += (dif + 'a' );
}
return shift;
}
void groupShiftedString(string str[], int n)
{
map< string, vector< int > > groupMap;
for ( int i = 0; i < n; i++)
{
string diffStr = getDiffString(str[i]);
groupMap[diffStr].push_back(i);
}
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;
}
}
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;
}
|
Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ShiftedStrings {
public static final int ALPHA = 26 ;
public static String getDiffString(String str) {
String shift = "" ;
for ( int i = 1 ; i < str.length(); i++) {
int dif = str.charAt(i) - str.charAt(i - 1 );
if (dif < 0 )
dif += ALPHA;
shift += ( char )(dif + 'a' );
}
return shift;
}
public static void groupShiftedString(String[] str) {
Map< String, List<Integer> > groupMap = new HashMap<>();
for ( int i = 0 ; i < str.length; i++) {
String diffStr = getDiffString(str[i]);
List<Integer> indices = groupMap.getOrDefault(diffStr, new ArrayList<>());
indices.add(i);
groupMap.put(diffStr, indices);
}
for (Map.Entry<String, List<Integer>> entry : groupMap.entrySet()) {
List<Integer> v = entry.getValue();
for ( int i = 0 ; i < v.size(); i++)
System.out.print(str[v.get(i)] + " " );
System.out.println();
}
}
public static void main(String[] args) {
String[] str = { "acd" , "dfg" , "wyz" , "yab" , "mop" , "bdfh" , "a" , "x" , "moqs" };
groupShiftedString(str);
}
}
|
Python3
ALPHA = 26
def getDiffString( str ):
shift = ""
for i in range ( 1 , len ( str )):
dif = ( ord ( str [i]) -
ord ( str [i - 1 ]))
if (dif < 0 ):
dif + = ALPHA
shift + = chr (dif + ord ( 'a' ))
return shift
def groupShiftedString( str ,n):
groupMap = {}
for i in range (n):
diffStr = getDiffString( str [i])
if diffStr not in groupMap:
groupMap[diffStr] = [i]
else :
groupMap[diffStr].append(i)
for it in groupMap:
v = groupMap[it]
for i in range ( len (v)):
print ( str [v[i]], end = " " )
print ()
str = [ "acd" , "dfg" , "wyz" ,
"yab" , "mop" , "bdfh" ,
"a" , "x" , "moqs" ]
n = len ( str )
groupShiftedString( str , n)
|
C#
using System;
using System.Collections.Generic;
public class ShiftedStrings {
public static readonly int ALPHA = 26;
public static 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;
shift += ( char )(dif + 'a' );
}
return shift;
}
public static void GroupShiftedString( string [] str)
{
Dictionary< string , List< int > > groupMap
= new Dictionary< string , List< int > >();
for ( int i = 0; i < str.Length; i++) {
string diffStr = GetDiffString(str[i]);
List< int > indices;
if (!groupMap.ContainsKey(diffStr)) {
indices = new List< int >();
}
else {
indices = groupMap[diffStr];
}
indices.Add(i);
groupMap[diffStr] = indices;
}
foreach (KeyValuePair< string , List< int > > entry in
groupMap)
{
List< int > v = entry.Value;
for ( int i = 0; i < v.Count; i++)
Console.Write(str[v[i]] + " " );
Console.WriteLine();
}
}
public static void Main( string [] args)
{
string [] str = { "acd" , "dfg" , "wyz" , "yab" , "mop" ,
"bdfh" , "a" , "x" , "moqs" };
GroupShiftedString(str);
}
}
|
Javascript
<script>
let ALPHA = 26;
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;
shift += (dif + 'a' );
}
return shift;
}
function groupShiftedString(str, n)
{
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);
}
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>" )
}
}
let str=[ "acd" , "dfg" , "wyz" , "yab" , "mop" ,
"bdfh" , "a" , "x" , "moqs" ];
let n = str.length;
groupShiftedString(str, n);
</script>
|
Output
a x
acd dfg wyz yab mop
bdfh moqs
Time Complexity: O(N*K), where N=length of string array and K is maximum length of string in string array
Auxiliary Space: O(N)
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Apr, 2023
Like Article
Save Article