Skip to content

Practice Decode the Message

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#2325
LeetCode Problem

Decode the Message

Problem Statement

Read key from left to right, ignoring spaces and letters already seen. Map its first distinct letter to a, the second to b, and so on through z. Decode message by replacing each letter with its mapped value while preserving every space. Return the decoded string. The key contains all 26 letters, so every message letter has a mapping. Approach: Build the substitution table in one scan of key, assigning the next alphabet letter only on a character's first appearance. Scan message once using this table. Time is O(key.length + message.length); the mapping requires constant space for 26 letters, apart from the output. Worked example: With the reversed alphabet as key, z maps to a, y to b, and x to c. Thus "zyx ab" becomes "abc zy". Repeating b at the start of the second key does not consume another mapping position.

Source: Decode the Message on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
key = "zyxwvutsrqponmlkjihgfedcba", message = "zyx ab"
Output
"abc zy"

# Example 2

Input
key = "b bacdefghijklmnopqrstuvwxyz", message = "b a cab"
Output
"a b cba"

Constraints

key has 26 to 2,000 characters and includes each lowercase English letter at least once.
message has 1 to 2,000 characters.
Both inputs contain only lowercase English letters and spaces.

Related LeetCode Problems

Practice more problems similar to Decode the Message.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.