Decode the Message — LeetCode 2325 Python Solution

EasyHash TableString
Problem
#2325
Pattern
Hash Map
Reading time
2 min

The 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 key as the order of the substitution table.

Example

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.

Python solution

Python
class Solution:
    def decodeMessage(self, key: str, message: str) -> str:
        d = {" ": " "}
        i = 0
        for c in key:
            if c not in d:
                d[c] = ascii_lowercase[i]
                i += 1
        return "".join(d[c] for c in message)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2325. Decode the Message is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2325. Decode the Message?
LeetCode 2325. Decode the Message is rated Easy on LeetCode.
What is the time complexity of LeetCode 2325. Decode the Message?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2325. Decode the Message?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2325. Decode the Message cover?
LeetCode 2325. Decode the Message is tagged Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview