πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- create an unordered map where the key is the character in key and the value is the actual mapped alphabetical character

πŸ€”What Did I Struggle With?

~

πŸ’‘ Explanation of Solution

- **Create a Hashmap**:
    - Use the characters from the `key` string to build the mapping for decoding:
        - The keys in the hashmap will be the characters from the `key` string.
        - The values will be the corresponding letters in the English alphabet (`'a'` to `'z'`).

- **Handle Redundant Characters**:    
    - Since `key` can have duplicate characters or spaces, skip over any character that has already been mapped.

- **Decode the Message**:    
    - For each character in the `message`, use the hashmap to decode it.
    - If the character is a space, it should remain unchanged.

βŒ› Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1) since we know that hashmap will only contain a max of 26 characters

πŸ’» Implementation of Solution

class Solution {
public:
    string decodeMessage(string key, string message) {
        unordered_map<char, char> charMap; // Hashmap for key-to-alphabet mapping
        char currentChar = 'a';            // Start mapping with 'a'
 
        // Build the hashmap
        for (char ch : key) {
            if (ch != ' ' && charMap.find(ch) == charMap.end()) {
                charMap[ch] = currentChar++;
            }
        }
 
        // Decode the message
        string decodedMessage = "";
        for (char ch : message) {
            if (ch == ' ') {
                decodedMessage += ' '; // Preserve spaces
            } else {
                decodedMessage += charMap[ch]; // Decode using the map
            }
        }
 
        return decodedMessage;
    }
};