We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Decrypt String from Alphabet to Integer Mapping

Difficulty: Easy


Problem Description

You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:

  • Characters ('a' to 'i') are represented by ('1' to '9') respectively.
  • Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.

Return the string formed after mapping.

Key Insights

  • The mapping is unique due to the constraints.
  • We need to differentiate between single digit mappings (1-9) and double digit mappings followed by '#' (10-26#).
  • We can iterate through the string and build the result based on the presence of '#' to determine the character mapping.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1), since we are using a constant amount of extra space for the result string.

Solution

To solve the problem, we will iterate through the input string and check for the presence of '#' to determine if we are dealing with a single-digit or double-digit mapping. We will use a result list to build the final output string efficiently, and then convert it to a string before returning.

  1. Initialize an empty list to store the characters.
  2. Loop through the string using an index.
  3. If the current character is followed by '#', convert the preceding two characters to the corresponding letter and add it to the result.
  4. If the current character is not followed by '#', convert the single character to the corresponding letter and add it to the result.
  5. Finally, return the joined list as the output string.

Code Solutions

def freqAlphabets(s: str) -> str:
    result = []
    i = 0
    while i < len(s):
        if i + 2 < len(s) and s[i + 2] == '#':
            # Convert two digits
            num = int(s[i:i + 2])
            result.append(chr(num + 96))  # 'a' is 97 in ASCII
            i += 3  # Move past the two digits and '#'
        else:
            # Convert single digit
            num = int(s[i])
            result.append(chr(num + 96))
            i += 1  # Move to the next character
    return ''.join(result)
← Back to All Questions