Decode the message

December 19, 2022

array-and-hashmap

Problem URL: Decode the message

We will use a hashmap to map the characters to their corresponding letters. Then iterate over the message, replace the characters with their corresponding letters and return the result.

class Solution:
    def decodeMessage(self, key: str, message: str) -> str:
        mapping = {' ': ' '}
        letters = 'abcdefghijklmnopqrstuvwxyz'

        i = 0
        for char in key:
            if char not in mapping:
                mapping[char] = letters[i]
                i += 1

        res = ''
        for char in message:
            res += mapping[char]

        return res

Time complexity: O(n)
Space complexity: O(n)