Skip to main content
Back to problems
#2325
Easy Algorithms

Decode the message

Hash Table String
85.8% acceptance
Feb 25, 2026
1128
113
You are given the strings key and message, which represent a cipher key and a secret message. 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 substituted using the table. Spaces are transformed to themselves. Return the decoded message.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn decode_message(key: String, message: String) -> String {
    let mut table = [' '; 26];
    let mut idx = 0u8;
    for c in key.chars() {
      if c != ' ' {
        let i = (c as u8 - b'a') as usize;
        if table[i] == ' ' {
          table[i] = (b'a' + idx) as char;
          idx += 1;
        }
      }
    }
    message.chars().map(|c| {
      if c == ' ' { ' ' } else { table[(c as u8 - b'a') as usize] }
    }).collect()
  }
}