Talentd
FleetCode
Make and follow sheets.Sign in

Hexspeak solution and explanation

EasyMathString4 min read57.5% acceptanceUpdated 23 Mar 2026Premium elsewhere, free here
#LeetCode 1271 | Hexspeak #JavaSleepy Cracker · 10:48 · 118 viewsWatch on YouTube
1 more video on this problem
  1. #LeetCode 1271 | Hexspeak #JavaSleepy Cracker · 10:48 · 118 views
  2. LeetCode 1271: HexspeakAlitaCode · 29:50 · 5 views

The problem

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].

Approach overview

Problem Overview: You receive a decimal number as a string. Convert it to hexadecimal, then transform the result into a special format called Hexspeak. In Hexspeak, digits 0 and 1 become letters O and I. Characters A–F stay the same. Any remaining digits (2-9) make the result invalid and you must return ERROR.

Approach 1: Built-in Hex Conversion + Simulation (O(n) time, O(n) space)

The direct solution converts the decimal string to a number, then generates its hexadecimal representation using built-in language utilities. After conversion, iterate through the hex string character by character. Replace '0' with 'O', replace '1' with 'I', and keep 'A'–'F' unchanged. If any digit from '2' to '9' appears, the string cannot form valid Hexspeak, so return ERROR immediately.

This works because hexadecimal already restricts characters to 0-9 and A-F. The validation step simply filters out digits that Hexspeak does not allow. The algorithm performs a single pass over the converted string, making it efficient and easy to implement in any language. The logic is essentially a small simulation of the transformation rules using basic string processing operations.

Approach 2: Manual Base-16 Conversion + Simulation (O(n) time, O(n) space)

Instead of relying on a built-in hex conversion, you can manually convert the number to base 16 using repeated division. Treat the input as a large integer (or convert it if it fits in standard types). Repeatedly divide the number by 16, store the remainder, and map each remainder to its hexadecimal character. Build the hex string in reverse order.

During or after building the hex representation, apply the same Hexspeak mapping rules: 0 → O, 1 → I, A–F remain unchanged, and digits 2–9 invalidate the result. This approach highlights the base conversion mechanics behind hexadecimal numbers and avoids language-specific helpers.

Although slightly more verbose, it demonstrates understanding of numeric base systems and digit extraction. The complexity remains linear in the number of hexadecimal digits because each division step produces one digit.

Recommended for interviews: The built-in conversion plus simulation approach is what most interviewers expect. It shows you recognize the problem as a straightforward transformation using string iteration and simple mapping rules. Mentioning the manual base-16 conversion demonstrates deeper understanding of number systems, but implementing it is usually unnecessary unless the interviewer specifically asks for it.

Solution

Convert the number to a hexadecimal string, then traverse the string, convert the number 0 to the letter O, and the number 1 to the letter I. Finally, check whether the converted string is valid.

The time complexity is O(log n), where n is the size of the decimal number represented by num.

class Solution:
    def toHexspeak 🔒(self, num: str) -> str:
        s = set('ABCDEFIO')
        t = hex(int(num))[2:].upper().replace('0', 'O').replace('1', 'I')
        return t if all(c in s for c in t) else 'ERROR'
class Solution {
    private static final Set<Character> S = Set.of('A', 'B', 'C', 'D', 'E', 'F', 'I', 'O');

    public String toHexspeak 🔒(String num) {
        String t
            = Long.toHexString(Long.valueOf(num)).toUpperCase().replace("0", "O").replace("1", "I");
        for (char c : t.toCharArray()) {
            if (!S.contains(c)) {
                return "ERROR";
            }
        }
        return t;
    }
}
class Solution {
public:
    string toHexspeak 🔒(string num) {
        stringstream ss;
        ss << hex << stol(num);
        string t = ss.str();
        for (int i = 0; i < t.size(); ++i) {
            if (t[i] >= '2' && t[i] <= '9') return "ERROR";
            if (t[i] == '0')
                t[i] = 'O';
            else if (t[i] == '1')
                t[i] = 'I';
            else
                t[i] = t[i] - 32;
        }
        return t;
    }
};
func toHexspeak 🔒(num string) string {
	x, _ := strconv.Atoi(num)
	t := strings.ToUpper(fmt.Sprintf("%x", x))
	t = strings.ReplaceAll(t, "0", "O")
	t = strings.ReplaceAll(t, "1", "I")
	for _, c := range t {
		if c >= '2' && c <= '9' {
			return "ERROR"
		}
	}
	return t
}
Try this approach in the editor

Complexity analysis

ApproachTimeSpaceWhen to Use
Built-in Hex Conversion + SimulationO(n)O(n)Best general solution. Simple implementation using built-in hex conversion and one pass validation.
Manual Base-16 Conversion + SimulationO(n)O(n)Useful when demonstrating understanding of base conversion or when built-in utilities are restricted.

Frequently asked questions

Is Hexspeak easy or hard?

Hexspeak is classified as an Easy problem. The core tasks are hexadecimal conversion and simple string validation. The challenge mainly comes from correctly handling the digit mapping and detecting invalid digits.

Hexspeak Python/Java solution

In Python or Java, convert the decimal string to a long integer, generate the hexadecimal representation, then iterate through the characters. Replace '0' with 'O', '1' with 'I', and allow 'A'–'F'. If any character from '2' to '9' appears, return "ERROR". The logic is identical across Python, Java, C++, and Go.

How to solve Hexspeak in O(n)?

Convert the decimal input to a hexadecimal string, then iterate through each character once. Replace '0' with 'O', '1' with 'I', keep 'A'–'F' unchanged, and reject digits '2'–'9'. Because each character is processed exactly once, the total complexity is O(n).

What is the best approach for Hexspeak?

The best approach converts the decimal string to hexadecimal and then simulates the Hexspeak transformation rules. Iterate through the hex string and map 0 → O and 1 → I while keeping A–F unchanged. If digits 2–9 appear, return ERROR. This runs in O(n) time and O(n) space.

Is Hexspeak asked at Google/Amazon/Meta?

Hexspeak is not among the most frequent interview questions at large companies, but it represents a common pattern: number base conversion followed by string validation. Variants of this pattern appear in interviews at companies like Amazon or Google when testing attention to edge cases and string manipulation.

What data structure is used in Hexspeak?

The solution primarily uses strings and simple character mapping. No complex data structures are required. The algorithm relies on iterating through the hexadecimal string and constructing a new result string.

What is the time complexity of Hexspeak?

The optimal solution runs in O(n) time where n is the number of characters in the hexadecimal representation. The algorithm converts the number to hex and scans the result once for validation and character replacement. Space complexity is O(n) for storing the output string.

Comments

Now write it yourselfClose this page and solve Hexspeak in the editor, without looking.
Practise Hexspeak