Decode the Message - Complete Solution Guide
Decode the Message is LeetCode problem 2325, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given the strings key and message , which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. Align the substitution table with the regular English alphabet. Each letter in message is then substituted using the table. Spaces ' ' are transformed to themselves. For example, given key = " hap p y bo y" (actual key would have at least
Detailed Explanation
The problem asks you to decode a secret message using a given cipher key. The key determines a substitution cipher: the first occurrence of each letter in the key maps to the next letter in the alphabet (a -> a, b -> b, etc.). Spaces remain spaces. The input consists of the key (a string containing all 26 letters at least once) and the message (a string to decode). The output is the decoded message.
Solution Approach
The provided solutions all use a similar approach: they iterate through the key, creating a mapping from each unique character (excluding spaces) to its corresponding decoded character. Then, they iterate through the message, using the mapping to decode each character. The result is built character by character into a new string.
Step-by-Step Algorithm
- Initialize a mapping data structure (hash table/array).
- Iterate through the key string:
- If a character is not a space and not already in the mapping:
- Add the character to the mapping, assigning it the next letter in the alphabet.
- Iterate through the message string:
- If the character is a space, append a space to the decoded message.
- Otherwise, look up the character in the mapping and append its decoded character to the decoded message.
- Return the decoded message.
Key Insights
- The problem requires creating a mapping from the characters in the key to their corresponding decoded characters. A hash table (or similar data structure) is ideal for efficient lookups.
- The order of letters in the key is crucial; only the first occurrence of each letter matters. Subsequent occurrences are ignored.
- Handling spaces correctly is important; they are not part of the substitution mapping.
Complexity Analysis
Time Complexity: O(m+n)
Space Complexity: O(1)
Topics
This problem involves: Hash Table, String.
Companies
Asked at: Coinbase, Tesla.