Decode the Message
EasyUpdated: Aug 2, 2025
Practice on:
Problem
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
keyas the order of the substitution table. - Align the substitution table with the regular English alphabet.
- Each letter in
messageis 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 one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a','a' -> 'b','p' -> 'c','y' -> 'd','b' -> 'e','o' -> 'f').
Return the decoded message.
Examples
Example 1

Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
Output: "this is a secret"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "_**the**_ _**quick**_ _**brown**_ _**f**_ o _**x**_ _**j**_ u _**mps**_ o _**v**_ er the _**lazy**_ _**d**_ o _**g**_ ".
Example 2

Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
Output: "the five boxing wizards jump quickly"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "_**eljuxhpwnyrdgtqkviszcfmabo**_ ".
Constraints
26 <= key.length <= 2000keyconsists of lowercase English letters and' '.keycontains every letter in the English alphabet ('a'to'z') at least once.1 <= message.length <= 2000messageconsists of lowercase English letters and' '.
Solution
Method 1 – Hash Map Substitution 1
Intuition
We can decode the message by building a mapping from the first appearance of each letter in the key to the regular English alphabet. Then, we substitute each character in the message using this mapping. This works because the key contains every letter at least once, so the mapping is always complete.
Approach
- Iterate through the key and record the first occurrence of each letter, mapping it to 'a', 'b', ..., 'z'.
- For each character in the message:
- If it is a space, keep it as is.
- Otherwise, substitute it using the mapping.
- Build and return the decoded message.
Code
C++
class Solution {
public:
string decodeMessage(string key, string message) {
unordered_map<char, char> mp;
char ch = 'a';
for (char c : key) {
if (c != ' ' && mp.find(c) == mp.end()) {
mp[c] = ch++;
}
}
string ans;
for (char c : message) {
ans += (c == ' ' ? ' ' : mp[c]);
}
return ans;
}
};
Go
func decodeMessage(key, message string) string {
mp := make(map[byte]byte)
ch := byte('a')
for i := 0; i < len(key); i++ {
c := key[i]
if c != ' ' && mp[c] == 0 {
mp[c] = ch
ch++
}
}
ans := make([]byte, len(message))
for i := 0; i < len(message); i++ {
if message[i] == ' ' {
ans[i] = ' '
} else {
ans[i] = mp[message[i]]
}
}
return string(ans)
}
Java
class Solution {
public String decodeMessage(String key, String message) {
Map<Character, Character> mp = new HashMap<>();
char ch = 'a';
for (char c : key.toCharArray()) {
if (c != ' ' && !mp.containsKey(c)) {
mp.put(c, ch++);
}
}
StringBuilder ans = new StringBuilder();
for (char c : message.toCharArray()) {
ans.append(c == ' ' ? ' ' : mp.get(c));
}
return ans.toString();
}
}
Kotlin
class Solution {
fun decodeMessage(key: String, message: String): String {
val mp = mutableMapOf<Char, Char>()
var ch = 'a'
for (c in key) {
if (c != ' ' && mp[c] == null) {
mp[c] = ch++
}
}
val ans = StringBuilder()
for (c in message) {
ans.append(if (c == ' ') ' ' else mp[c])
}
return ans.toString()
}
}
Python
class Solution:
def decodeMessage(self, key: str, message: str) -> str:
mp: dict[str, str] = {}
ch = ord('a')
for c in key:
if c != ' ' and c not in mp:
mp[c] = chr(ch)
ch += 1
ans = []
for c in message:
ans.append(' ' if c == ' ' else mp[c])
return ''.join(ans)
Rust
impl Solution {
pub fn decode_message(key: String, message: String) -> String {
use std::collections::HashMap;
let mut mp = HashMap::new();
let mut ch = b'a';
for c in key.bytes() {
if c != b' ' && !mp.contains_key(&c) {
mp.insert(c, ch);
ch += 1;
}
}
message.bytes().map(|c| {
if c == b' ' { ' ' } else { mp[&c] as char }
}).collect()
}
}
TypeScript
class Solution {
decodeMessage(key: string, message: string): string {
const mp: Record<string, string> = {};
let ch = 97;
for (const c of key) {
if (c !== ' ' && !(c in mp)) {
mp[c] = String.fromCharCode(ch++);
}
}
let ans = '';
for (const c of message) {
ans += c === ' ' ? ' ' : mp[c];
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n + m), where n is the length of key and m is the length of message, as we scan both once. - 🧺 Space complexity:
O(1), since the mapping size is constant (26 letters).