Group Shifted Strings - CPP Solution

1. Introduction

In this post, we delve into a fascinating string processing problem in C++ known as "Group Shifted Strings". This problem combines concepts of string manipulation, hashing, and groupings based on specific criteria, making it an intriguing challenge for anyone interested in algorithms and data structures.

Problem

The task is to group all strings that belong to the same shifting sequence. A string's shift sequence is defined by the difference between each character and its subsequent character. For example, "abc" and "bcd" belong to the same group because their shift sequences are the same.

2. Solution Steps

1. Iterate through each string in the input list.

2. For each string, calculate its shift sequence.

3. Use a hash map to group strings with the same shift sequence.

4. For the shift sequence, use a string representing the difference between each character and its next character.

5. Add each string to the corresponding group in the hash map.

6. Finally, extract all the groups from the hash map and return them.

3. Code Program

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

// Function to calculate the shift key for a string
string getShiftKey(const string &str) {
    string key = "";
    for (int i = 1; i < str.size(); i++) {
        int diff = str[i] - str[i - 1];
        if (diff < 0) diff += 26;
        key += diff + ',';
    }
    return key;
}

// Function to group shifted strings
vector<vector<string>> groupStrings(vector<string>& strings) {
    unordered_map<string, vector<string>> groups;
    for (const string &str : strings) {
        string key = getShiftKey(str);
        groups[key].push_back(str);
    }

    vector<vector<string>> result;
    for (auto &group : groups) {
        result.push_back(group.second);
    }
    return result;
}

int main() {
    vector<string> strings = {"abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"};
    vector<vector<string>> groupedStrings = groupStrings(strings);

    cout << "Grouped Shifted Strings:" << endl;
    for (const auto &group : groupedStrings) {
        for (const string &str : group) {
            cout << str << " ";
        }
        cout << endl;
    }
    return 0;
}

Output:

Grouped Shifted Strings:
abc bcd xyz
acef
az ba
a z

Explanation:

1. Each string in the input ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"] is processed.

2. The shift sequence for each string is calculated. For instance, "abc" and "bcd" have the same shift sequence.

3. Strings are grouped based on their shift sequences using a hash map.

4. The output groups strings such that each group's strings are shifted versions of each other.

5. The function efficiently categorizes the strings into groups of shifted sequences, as seen in the output.


Comments