Taro Logo

Hexspeak

Easy
Asked by:
Virtu Financial
1 view
Topics:
Strings

A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit '0' with the letter 'O', and the digit '1' with the letter 'I'. Such a representation is valid if and only if it consists only of the letters in the set {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}.

Given a string num representing a decimal integer n, return the Hexspeak representation of n if it is valid, otherwise return "ERROR".

Example 1:

Input: num = "257"
Output: "IOI"
Explanation: 257 is 101 in hexadecimal.

Example 2:

Input: num = "3"
Output: "ERROR"

Constraints:

  • 1 <= num.length <= 12
  • num does not contain leading zeros.
  • num represents an integer in the range [1, 1012].

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum size or value of the input string `num`? Could it exceed standard integer or long integer limits?
  2. Can the input string `num` represent a negative integer, or are we guaranteed to receive only non-negative numbers?
  3. Could the input string contain leading zeros, and if so, how should they be handled in the hexadecimal and Hexspeak conversion?
  4. Are the resulting letters in the Hexspeak output expected to be uppercase, or could lowercase letters be present in the input or output?
  5. What should be returned if the input string is empty or null?

Brute Force Solution

Approach

The brute force approach to solving the Hexspeak problem involves converting a given number into its hexadecimal representation and checking every single character to see if it forms a valid word. If any character fails to translate into a valid Hexspeak letter, we completely reject the number.

Here's how the algorithm would work step-by-step:

  1. Take the starting number and translate it entirely into its hexadecimal format, which uses numbers zero through nine and letters A through F.
  2. Look at every single digit and letter of this newly converted representation one by one.
  3. For each character, check if it is either a zero, a one, or one of the allowed letters that represent a valid Hexspeak word.
  4. If you encounter any character that is not allowed, immediately stop and mark this number as invalid.
  5. If you successfully check every single character and find that all of them are valid Hexspeak letters or numbers, declare this as a success.
  6. Return the final translated word, making sure to replace any zeros with the letter O and any ones with the letter I, just as the rules of Hexspeak require.

Code Implementation

def convert_to_hexspeak(number_string):
    decimal_number = int(number_string)
    
    hexadecimal_string = hex(decimal_number)[2:].upper()

    # We map hex digits to Hexspeak to validate the allowed character set strictly
    allowed_hexspeak_map = {'0': 'O', '1': 'I', 'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'E': 'E', 'F': 'F'}

    translated_characters = []

    for current_character in hexadecimal_string:
        # Any character outside the allowed set invalidates the entire number for Hexspeak
        if current_character not in allowed_hexspeak_map:
            return "ERROR"

        translated_characters.append(allowed_hexspeak_map[current_character])

    # Joining characters back ensures we return the complete translated word as required
    return "".join(translated_characters)

Big(O) Analysis

Time Complexity
O(log n) – The time complexity is driven by the conversion of the input number n into its hexadecimal string and the subsequent linear scan of that resulting string. Since hexadecimal representation divides the number by 16 at each step, the length of the string is proportional to log16(n). Checking each character of this string takes time proportional to its length. Therefore, the total operations approximate c * log16(n) where c is a small constant factor, which simplifies to O(log n).
Space Complexity
O(log N) – To determine the space complexity, we analyze the auxiliary memory required by the conversion steps. Generating the hexadecimal string representation of the input number N creates a temporary character string whose length grows logarithmically with the value of N. Additionally, iterating through the characters and building the final translated word requires storage proportional to this same hexadecimal string length. Therefore, the extra memory used by these intermediate strings scales as O(log N) relative to the magnitude of the input number.

Optimal Solution

Approach

The optimal approach to solving Hexspeak involves translating a given number into its hexadecimal representation, and then checking if every single digit can be validly mapped to an allowed letter or the number one and zero. If any forbidden digit is found, the result is rejected; otherwise, all matching digits are swapped for their letter equivalents to form the secret word.

Here's how the algorithm would work step-by-step:

  1. Take the input number and convert it into base sixteen, which uses digits from zero through nine and letters up to the letter represented by fifteen.
  2. Look at every single digit or letter in this converted representation one by one.
  3. Check if the current character is a zero, a one, or any of the allowed letters that look like letters.
  4. If you encounter any digit that is not allowed, immediately stop and declare that the number cannot be translated into Hexspeak.
  5. If the character is a zero, swap it out for the letter corresponding to the capital letter O.
  6. If the character is a one, swap it out for the letter corresponding to the capital letter I.
  7. Once all characters have been successfully checked and swapped, combine them together to reveal the final Hexspeak word.

Code Implementation

def convert_to_hexspeak(input_number):
    decimal_integer = int(input_number)
    hexadecimal_string = hex(decimal_integer)[2:].upper()
    
    # We map only specific valid digits to ensure the result forms a readable word.
    valid_character_map = {'0': 'O', '1': 'I', 'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'E': 'E', 'F': 'F'}
    translated_characters = []
    
    for current_character in hexadecimal_string:
        # Any forbidden digit immediately invalidates the number for Hexspeak translation.
        if current_character not in valid_character_map:
            return "ERROR"
            
        translated_characters.append(valid_character_map[current_character])
        
    # Combining all successfully translated characters reveals the final secret word.
    return "".join(translated_characters)

Big(O) Analysis

Time Complexity
O(log n) – The input is an integer n, and the cost is driven by converting this number into its hexadecimal string representation. Converting an integer to base sixteen takes a number of divisions proportional to the number of digits, which is bounded by the logarithm base 16 of n. We then iterate over each character of this resulting hexadecimal string, performing a constant-time check and substitution for each character. Since the length of the hexadecimal string is proportional to log(n), the total operations scale logarithmically with the value of the input number n, simplifying to O(log n).
Space Complexity
O(N) – To generate the final Hexspeak word, the algorithm constructs an auxiliary string or character array to store the converted and mapped hexadecimal characters. As the input number grows, its hexadecimal representation scales in length proportionally to the logarithm of the input magnitude, which we denote as N. Consequently, storing these intermediate characters and building the resulting word requires auxiliary memory that grows linearly with respect to N. Since no other dynamic data structures or recursive calls are utilized, this character storage dominates the auxiliary space complexity.

Edge Cases

Input represents the decimal number 0
How to Handle:
Converting 0 to hex yields '0', which becomes 'O' and is correctly validated as Hexspeak.
Input represents the decimal number 1
How to Handle:
Converting 1 to hex yields '1', which becomes 'I' and is correctly validated as Hexspeak.
Input contains digits like 2 through 9 that are not valid Hexspeak characters
How to Handle:
The validation check detects invalid characters and returns the ERROR string.
Extremely large numbers represented as strings exceeding standard 64-bit integer limits
How to Handle:
The solution must parse the input using arbitrary-precision integer arithmetic to prevent overflow before conversion.
Input string contains leading zeros
How to Handle:
Standard decimal parsing will correctly evaluate the numeric value while preserving the integrity of the conversion.
Negative numbers passed as input strings
How to Handle:
Since the problem implies standard positive decimal integers, negative prefixes should either trigger an ERROR or be handled according to strict constraints.
Valid hexadecimal letters A through F mixed with 0 and 1
How to Handle:
The conversion correctly leaves letters A-F untouched while replacing 0 with O and 1 with I.