Decode the Message - 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:

  1. Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
  2. Align the substitution table with the regular English alphabet.
  3. Each letter in message is then substituted using the table.
  4. Spaces ' ' are transformed to themselves.

For example, given key = "happy boy" (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.

Input & Output

Example 1 — Basic Substitution
$ Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
Output: this is a secret
💡 Note: Key contains all 26 letters. First unique chars: t→a, h→b, e→c, q→d, u→e, i→f, c→g, k→h, etc. Decoding 'v'→'s', 'k'→'h', 'b'→'i', 's'→'t' gives 'this is a secret'
Example 2 — With Spaces
$ Input: key = "happy boy", message = "h p"
Output: a e
💡 Note: Key gives mapping h→a, a→b, p→c, y→d, b→e, o→f. Message 'h p' becomes 'a e' (spaces preserved)
Example 3 — Single Character
$ Input: key = "abcdefghijklmnopqrstuvwxyz", message = "z"
Output: z
💡 Note: Key is regular alphabet, so z→z (26th letter maps to 26th position)

Constraints

  • 1 ≤ key.length ≤ 105
  • 1 ≤ message.length ≤ 104
  • key contains every letter of the English alphabet at least once
  • key and message consist of lowercase English letters and spaces

Visualization

Tap to expand
Decode the Message: Cipher Key → Substitution Table → Decoded MessageKey: "the quick brown fox jumps"thequFirst unique chars from keyabcdeMaps to alphabet positionsMessage: "hu" → "be"hubeDecoded Message: "be"
Understanding the Visualization
1
Extract Key
Get first occurrence of each letter from key string
2
Build Map
Map key characters to alphabet positions
3
Decode
Transform message using substitution table
Key Takeaway
🎯 Key Insight: Build a character mapping from the unique letters in key to alphabet positions for fast O(1) substitution
Asked in
Google 15 Meta 12 Amazon 8
28.5K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen