# Group Shifted Strings in C++

Suppose we have a string, we can "shift" each of its letter to its successive letter, so: "abc" can be changed to "bcd". We can keep doing this operation which forms the sequence: "abc" -> "bcd" -> ... -> "xyz". If we have a list of non-empty strings that contains only lowercase alphabets, we have to group all strings that belong to the same shifting sequence.

So, if the input is like ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], then the output will be [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ]

To solve this, we will follow these steps −

• Define one map m

• Define one 2D array ret

• for initialize i := 0, when i < size of strings, update (increase i by 1), do −

• key := blank string

• for initialize j := 1, when j < size of strings[i], update (increase j by 1), do −

• diff := strings[i, j] - strings[i, j - 1]

• if diff < 0, then −

• diff := diff + 26

• key := key concatenate "#" concatenate diff as string

• insert strings[i] at the end of m[key]

• for each element it in m, do −

• insert value of it at the end of ret

• (increase it by 1)

• return ret

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto< > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<vector<string>> groupStrings(vector<string<& strings) {
unordered_map<string, vector<string> > m;
vector<vector<string< > ret;
for (int i = 0; i < strings.size(); i++) {
string key = "";
for (int j = 1; j < strings[i].size(); j++) {
int diff = strings[i][j] - strings[i][j - 1];
if (diff < 0)
diff += 26;
key += "#" + to_string(diff);
}
m[key].push_back(strings[i]);
}
unordered_map<string, vector<string< >::iterator it = m.begin();
while (it != m.end()) {
ret.push_back(it->second);
it++;
}
return ret;
}
};
main(){
Solution ob;
vector<string< v = {"abc","bcd","acef","xyz","az","ba","a","z"};
print_vector(ob.groupStrings(v));
}

## Input

{"abc","bcd","acef","xyz","az","ba","a","z"}

## Output

[[az, ba, ],[a, z, ],[abc, bcd, xyz, ],[acef, ],]

Updated on: 18-Nov-2020

114 Views