Problem Description
Given a cipher key and a secret message, the task is to decode the message using a substitution cipher. The substitution table is generated by taking the first appearance of every lowercase English letter in the key (ignoring spaces) and mapping them in order to the regular alphabet (a to z). Each character in the message is then replaced accordingly, and spaces are preserved.
Key Insights
- The key string might contain duplicate letters and spaces; only the first occurrence of each letter matters.
- Build a mapping (substitution table) from the key letters to the alphabet letters.
- Loop through the message and replace each letter using the created mapping.
- Maintain spaces in the message unchanged.
Space and Time Complexity
Time Complexity: O(n + m) where n is the length of the key and m is the length of the message. Space Complexity: O(1) as the mapping holds at most 26 key-value pairs; additional space for the output message is O(m).
Solution
We first create a substitution table by iterating over the key string and collecting the first occurrence of each letter, ignoring spaces. These collected letters will be mapped to the alphabet from 'a' to 'z'. Then, for each character in the message, if it is a space, we leave it as is; otherwise, we substitute it using the table. This approach uses a hash map (or dictionary) for fast letter lookups, ensuring efficient substitution.