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

Hexspeak

Number: 1199

Difficulty: Easy

Paid? Yes

Companies: Virtu Financial


Problem Description

Given a decimal number as a string, convert it to its Hexspeak representation. First, convert the number to an uppercase hexadecimal string; then replace every '0' with 'O' and every '1' with 'I'. The result is valid only if it contains characters solely from the set {A, B, C, D, E, F, I, O}. If the result includes any other character, return "ERROR", otherwise return the valid Hexspeak string.


Key Insights

  • Convert the input decimal string to an integer.
  • Use built-in functions to convert the integer to a hexadecimal string in uppercase.
  • Replace '0' with 'O' and '1' with 'I' in the hexadecimal string.
  • Validate that every character in the result is in the allowed set {A, B, C, D, E, F, I, O}.
  • Return "ERROR" if any character is invalid; otherwise, return the transformed string.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the hexadecimal string (processing each character once).
Space Complexity: O(n) for storing the hexadecimal and final transformed string.


Solution

We start by parsing the input string into an integer, then convert this integer into its hexadecimal representation using built-in conversion functions. We immediately convert this string to uppercase, perform the required replacements (converting '0' to 'O' and '1' to 'I'), and then iterate over every character to check if it is in the allowed set. The allowed set is implemented as a collection (for example, a set or hash set) to allow O(1) membership checks. If any character is not allowed, we return "ERROR". Otherwise, the final Hexspeak string is returned.


Code Solutions

# Python solution for Hexspeak problem

def hexspeak(num: str) -> str:
    # Step 1: Convert the input string to an integer
    number = int(num)
    # Step 2: Convert the integer to an uppercase hexadecimal string without the '0x' prefix
    hex_str = format(number, 'X')
    # Step 3: Replace '0' with 'O' and '1' with 'I'
    hex_str = hex_str.replace('0', 'O').replace('1', 'I')
    # Step 4: Validate each character against the allowed set
    allowed_chars = set(['A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'])
    for ch in hex_str:
        if ch not in allowed_chars:
            return "ERROR"  # Return error if any character is invalid
    return hex_str

# Example usage:
# print(hexspeak("257"))
← Back to All Questions