Codepath

Secret Beach

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
    • To decode a message using a cipher key based on the first appearance of letters in the key.
    • What input is provided?
    • Two strings, key and message.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Create a substitution table using the first appearances of letters in key, then decode the message.

1) Create a dictionary `substitution_table` to map the letters in `key` to the English alphabet.
2) Iterate through `key` and map each letter to the alphabet if it has not been mapped already.
3) Iterate through `message` and use the substitution table to decode each character.
4) Return the decoded message.

⚠️ Common Mistakes

  • Not correctly handling spaces or missing characters in the substitution table.

I-mplement

def decode_message(key, message):
    # Create the substitution table
    substitution_table = {}
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    used_chars = set()

    index = 0
    for char in key:
        if char.isalpha() and char not in used_chars:
            substitution_table[char] = alphabet[index]
            used_chars.add(char)
            index += 1
            if index == 26:
                break

    # Decode the message
    decoded_message = []
    for char in message:
        if char == ' ':
            decoded_message.append(' ')
        else:
            decoded_message.append(substitution_table.get(char, char))

    return ''.join(decoded_message)
Fork me on GitHub