Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1271. Hexspeak - Leetcode Solution

Code Implementation

class Solution:
    def toHexspeak(self, num: str) -> str:
        n = int(num)
        hex_str = hex(n)[2:].upper()
        result = []
        for ch in hex_str:
            if ch == '0':
                result.append('O')
            elif ch == '1':
                result.append('I')
            elif ch in 'ABCDEF':
                result.append(ch)
            else:
                return "ERROR"
        return ''.join(result)
      
class Solution {
public:
    string toHexspeak(string num) {
        long long n = stoll(num);
        string hex = "";
        while (n > 0) {
            int rem = n % 16;
            if (rem == 0)
                hex += 'O';
            else if (rem == 1)
                hex += 'I';
            else if (rem >= 10 && rem <= 15)
                hex += 'A' + (rem - 10);
            else
                return "ERROR";
            n /= 16;
        }
        reverse(hex.begin(), hex.end());
        return hex;
    }
};
      
class Solution {
    public String toHexspeak(String num) {
        long n = Long.parseLong(num);
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            long rem = n % 16;
            if (rem == 0)
                sb.append('O');
            else if (rem == 1)
                sb.append('I');
            else if (rem >= 10 && rem <= 15)
                sb.append((char)('A' + (rem - 10)));
            else
                return "ERROR";
            n /= 16;
        }
        return sb.reverse().toString();
    }
}
      
var toHexspeak = function(num) {
    let n = BigInt(num);
    let hex = n.toString(16).toUpperCase();
    let result = '';
    for (let ch of hex) {
        if (ch === '0') result += 'O';
        else if (ch === '1') result += 'I';
        else if ('ABCDEF'.includes(ch)) result += ch;
        else return "ERROR";
    }
    return result;
};
      

Problem Description

Given a decimal string num representing a positive integer, you are required to convert it to a "Hexspeak" string. The process involves:

  • Converting num to its hexadecimal representation (without the 0x prefix).
  • Replacing every 0 with O and every 1 with I.
  • All other digits must be uppercase hexadecimal letters (A to F).
  • If any digit in the hexadecimal representation is not valid in Hexspeak (i.e., not 0, 1, or A to F), return "ERROR".

Only one valid output is possible for each input. You do not need to reuse or rearrange any elements.

Thought Process

At first glance, the problem seems to be a simple base conversion task. However, the twist comes from the "Hexspeak" rules: only certain digits are allowed in the output, and others (like 2-9) are forbidden.

A brute-force approach would be to convert the number to hexadecimal, then check each character and build the Hexspeak string if possible. If any forbidden digit appears, we immediately return "ERROR".

Optimization is straightforward because:

  • Hexadecimal conversion is fast and built-in for most languages.
  • Checking and replacing characters is a simple linear scan.
There is no need for more complex data structures or algorithms. The focus is on careful string manipulation and validation.

Solution Approach

Let's break down the steps to solve the problem:

  1. Convert the input string to an integer:
    • Since the input is a string, parse it as an integer (or BigInt if needed).
  2. Convert the integer to a hexadecimal string:
    • Use language-specific functions to get the hex representation (e.g., hex() in Python, toString(16) in JavaScript).
    • Remove any leading 0x if present, and convert to uppercase.
  3. Build the Hexspeak string:
    • Iterate through each character in the hexadecimal string.
    • If the character is 0, replace it with O.
    • If the character is 1, replace it with I.
    • If the character is one of A to F, keep it as is.
    • If it's any other character (i.e., 2 to 9), return "ERROR".
  4. Return the result:
    • If all characters are valid, join and return the Hexspeak string.

This approach is efficient and easy to implement. We use simple string operations and a single pass through the hexadecimal digits, making it both readable and fast.

Example Walkthrough

Let's walk through an example to see how the solution works step by step.

Example Input: num = "257"

  1. Convert to integer:
    • 257 (decimal)
  2. Convert to hexadecimal:
    • 257 in hex is 101
  3. Build Hexspeak string:
    • First character: 1I
    • Second character: 0O
    • Third character: 1I
  4. Result:
    • Hexspeak: IOI

Another Example: num = "3"

  • 3 in hex is 3, which is not allowed in Hexspeak.
  • So, we return "ERROR".

Time and Space Complexity

Brute-force Approach:

  • Still requires converting the number to hex and checking each digit, so the time complexity is O(L), where L is the length of the hexadecimal string.
  • Space complexity is also O(L) for storing the result.
Optimized Approach (as described above):
  • Time complexity: O(L) (one pass through the hexadecimal string).
  • Space complexity: O(L) (for the output string).

There is no significant difference between brute-force and optimized approaches due to the simplicity of the task.

Summary

The Hexspeak problem is a straightforward exercise in number base conversion and string manipulation. By leveraging built-in hexadecimal conversion and simple character checks, we can efficiently determine if a number's hex representation can be transformed into Hexspeak. The key insight is to validate each digit and perform substitutions as specified, returning "ERROR" immediately if any invalid digit is found. The solution is clean, efficient, and easy to understand, making it a great example of applying basic programming concepts to meet unique problem constraints.