LeetCode 2325: Decode the Message Solution

Master LeetCode problem 2325 (Decode the Message), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2325. Decode the Message

Problem Explanation

Explanation:

To decode the message, we first need to create a substitution table based on the given key string. We will use the first appearance of all 26 lowercase English letters in the key as the order of the substitution table. Then, we can decode the message by substituting each letter in the message using this table. Spaces remain unchanged in the decoded message.

  1. Create a substitution table based on the key string.
  2. Iterate through the message and substitute each letter using the table.
  3. Maintain spaces as they are in the decoded message.

Time Complexity:
Constructing the substitution table takes O(n) time, where n is the length of the key. Substituting each letter in the message takes O(m) time, where m is the length of the message. Therefore, the overall time complexity is O(n + m).

Space Complexity:
The space complexity is O(1) for the substitution table as it has a fixed size of 26 letters. The space complexity for the decoded message is also O(1) as we are not using any extra space for it.

:

Solution Code

class Solution {
    public String decodeMessage(String key, String message) {
        char[] table = new char[26];
        Arrays.fill(table, ' ');

        for (int i = 0; i < key.length(); i++) {
            char ch = key.charAt(i);
            if (ch != ' ' && table[ch - 'a'] == ' ') {
                table[ch - 'a'] = (char)('a' + i);
            }
        }

        StringBuilder decoded = new StringBuilder();
        for (char ch : message.toCharArray()) {
            if (ch == ' ') {
                decoded.append(' ');
            } else {
                decoded.append(table[ch - 'a']);
            }
        }

        return decoded.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2325 (Decode the Message)?

This page provides optimized solutions for LeetCode problem 2325 (Decode the Message) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2325 (Decode the Message)?

The time complexity for LeetCode 2325 (Decode the Message) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2325 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2325 in Java, C++, or Python.

Back to LeetCode Solutions