1271. Hexspeak 🔒
Problem Description
You need to convert a decimal number to a special hexadecimal format called "Hexspeak".
The conversion process works as follows:
- First, convert the decimal number to its hexadecimal representation (using uppercase letters A-F)
- Replace all occurrences of digit
'0'
with the letter'O'
- Replace all occurrences of digit
'1'
with the letter'I'
After these replacements, the result is considered valid "Hexspeak" only if it contains exclusively letters from the set {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}
. This means no other digits (2-9) can appear in the hexadecimal representation after the replacements.
Given a string num
representing a decimal integer, you need to:
- Convert it to Hexspeak following the rules above
- Return the Hexspeak representation if it's valid
- Return
"ERROR"
if the result contains any characters outside the allowed set
For example:
- If the decimal number converts to hex
"1A0B"
, after replacements it becomes"IAOB"
which contains only valid letters, so it's valid Hexspeak - If the decimal number converts to hex
"3A2"
, after replacements it becomes"3A2"
which contains the digit'3'
and'2'
, making it invalid, so return"ERROR"
Intuition
The problem is essentially asking us to perform a series of transformations and then validate the result. Let's think through what we need to do step by step.
First, we need to convert a decimal number to hexadecimal. Python provides a built-in hex()
function that does this conversion for us. The result will be in lowercase with a '0x'
prefix, so we'll need to handle that.
Next, we need to replace specific digits with letters. The replacements are straightforward: '0'
becomes 'O'
and '1'
becomes 'I'
. This is a simple string replacement operation.
The key insight is recognizing what makes a valid Hexspeak string. After our replacements, the only valid characters are {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}
. Notice that:
- Letters
A-F
come naturally from hexadecimal conversion 'I'
and'O'
come from our replacements of'1'
and'0'
- Any other digits
2-9
in the hexadecimal representation would make it invalid
So our validation strategy becomes: after performing all transformations, check if every character in the resulting string belongs to the valid set. If any character doesn't belong (like digits 2-9
), we know it's not valid Hexspeak.
This leads us to a clean solution: convert to hex, apply replacements, then validate by checking if all characters are in our allowed set. Using Python's all()
function with a set membership check gives us an elegant way to validate every character at once.
Learn more about Math patterns.
Solution Approach
The solution follows a straightforward simulation approach with these steps:
-
Define the valid character set: Create a set
s
containing all valid Hexspeak characters:{'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}
. Using a set allows for O(1) membership checking. -
Convert decimal to hexadecimal:
- First convert the input string
num
to an integer usingint(num)
- Apply Python's
hex()
function to get the hexadecimal representation - The
hex()
function returns a string like'0x1a2b'
, so we slice from index 2 onwards using[2:]
to remove the'0x'
prefix
- First convert the input string
-
Transform to Hexspeak format:
- Convert the hexadecimal string to uppercase using
.upper()
since Hexspeak requires uppercase letters - Replace all occurrences of
'0'
with'O'
using.replace('0', 'O')
- Replace all occurrences of
'1'
with'I'
using.replace('1', 'I')
- These replacements can be chained together for cleaner code
- Convert the hexadecimal string to uppercase using
-
Validate the result:
- Use Python's
all()
function with a generator expression to check if every characterc
in the transformed stringt
exists in our valid sets
- The expression
all(c in s for c in t)
returnsTrue
only if every character is valid - If valid, return the transformed string
t
; otherwise, return'ERROR'
- Use Python's
The entire solution is implemented in a single line (after defining the valid set), making it both concise and efficient. The time complexity is O(n) where n is the length of the hexadecimal representation, and the space complexity is O(1) for the fixed-size set plus O(n) for the string manipulations.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with the decimal number "257"
:
-
Define valid character set:
- We create
s = {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}
- We create
-
Convert decimal to hexadecimal:
- Convert string
"257"
to integer:257
- Apply
hex(257)
which gives us"0x101"
- Remove the
"0x"
prefix:"101"
- Convert string
-
Transform to Hexspeak format:
- Convert to uppercase:
"101"
→"101"
(no change since digits remain digits) - Replace
'0'
with'O'
:"101"
→"1O1"
- Replace
'1'
with'I'
:"1O1"
→"IOI"
- Convert to uppercase:
-
Validate the result:
- Check each character in
"IOI"
:'I'
is in our valid set ✓'O'
is in our valid set ✓'I'
is in our valid set ✓
- Since all characters are valid, return
"IOI"
- Check each character in
Now let's see an example that results in "ERROR"
. Consider decimal number "747"
:
-
Convert to hex:
hex(747)
gives"0x2eb"
, remove prefix →"2eb"
-
Transform:
- Uppercase:
"2EB"
- Replace
'0'
with'O'
:"2EB"
(no zeros to replace) - Replace
'1'
with'I'
:"2EB"
(no ones to replace)
- Uppercase:
-
Validate:
- Check
'2'
→ NOT in valid set ✗ - Since we found an invalid character, return
"ERROR"
- Check
The key insight is that any hexadecimal digit from 2-9 will cause the validation to fail, while 0 and 1 get transformed into valid letters O and I.
Solution Implementation
1class Solution:
2 def toHexspeak(self, num: str) -> str:
3 # Define valid characters for hexspeak: A-F plus I (replacing 1) and O (replacing 0)
4 valid_chars = set('ABCDEFIO')
5
6 # Convert string number to integer, then to hexadecimal
7 # Remove '0x' prefix with [2:] and convert to uppercase
8 hex_string = hex(int(num))[2:].upper()
9
10 # Replace digits 0 and 1 with letters O and I respectively
11 hex_string = hex_string.replace('0', 'O').replace('1', 'I')
12
13 # Check if all characters in the resulting string are valid hexspeak characters
14 # Return the string if valid, otherwise return 'ERROR'
15 if all(char in valid_chars for char in hex_string):
16 return hex_string
17 else:
18 return 'ERROR'
19
1class Solution {
2 // Valid characters allowed in Hexspeak
3 private static final Set<Character> VALID_HEXSPEAK_CHARS = Set.of('A', 'B', 'C', 'D', 'E', 'F', 'I', 'O');
4
5 /**
6 * Converts a decimal number to Hexspeak format.
7 * Hexspeak is a hexadecimal representation where:
8 * - '0' is replaced with 'O'
9 * - '1' is replaced with 'I'
10 * - Only letters A-F, I, and O are allowed
11 *
12 * @param num The decimal number as a string
13 * @return The Hexspeak representation, or "ERROR" if invalid
14 */
15 public String toHexspeak(String num) {
16 // Convert decimal string to hexadecimal and transform to uppercase
17 String hexString = Long.toHexString(Long.valueOf(num)).toUpperCase();
18
19 // Replace digits 0 and 1 with their Hexspeak equivalents
20 String hexspeakCandidate = hexString.replace("0", "O").replace("1", "I");
21
22 // Validate that all characters are valid Hexspeak characters
23 for (char character : hexspeakCandidate.toCharArray()) {
24 if (!VALID_HEXSPEAK_CHARS.contains(character)) {
25 return "ERROR";
26 }
27 }
28
29 return hexspeakCandidate;
30 }
31}
32
1class Solution {
2public:
3 string toHexspeak(string num) {
4 // Convert the decimal string to hexadecimal string
5 stringstream ss;
6 ss << hex << stol(num);
7 string hexString = ss.str();
8
9 // Process each character in the hexadecimal string
10 for (int i = 0; i < hexString.size(); ++i) {
11 // Check if the character is a digit from 2 to 9 (invalid for hexspeak)
12 if (hexString[i] >= '2' && hexString[i] <= '9') {
13 return "ERROR";
14 }
15
16 // Replace '0' with 'O' for hexspeak
17 if (hexString[i] == '0') {
18 hexString[i] = 'O';
19 }
20 // Replace '1' with 'I' for hexspeak
21 else if (hexString[i] == '1') {
22 hexString[i] = 'I';
23 }
24 // Convert lowercase hex letters (a-f) to uppercase (A-F)
25 else {
26 hexString[i] = hexString[i] - 32;
27 }
28 }
29
30 return hexString;
31 }
32};
33
1function toHexspeak(num: string): string {
2 // Convert the decimal string to a number and then to hexadecimal string
3 const decimalValue = parseInt(num, 10);
4 let hexString = decimalValue.toString(16);
5
6 // Build the result string by processing each character
7 let result = "";
8
9 for (let i = 0; i < hexString.length; i++) {
10 const char = hexString[i];
11
12 // Check if the character is a digit from 2 to 9 (invalid for hexspeak)
13 if (char >= '2' && char <= '9') {
14 return "ERROR";
15 }
16
17 // Replace '0' with 'O' for hexspeak
18 if (char === '0') {
19 result += 'O';
20 }
21 // Replace '1' with 'I' for hexspeak
22 else if (char === '1') {
23 result += 'I';
24 }
25 // Convert lowercase hex letters (a-f) to uppercase (A-F)
26 else {
27 result += char.toUpperCase();
28 }
29 }
30
31 return result;
32}
33
Time and Space Complexity
Time Complexity: O(log n)
, where n
is the size of the decimal number represented by num
.
- Converting string to integer:
O(m)
wherem
is the length of the stringnum
- Converting integer to hexadecimal using
hex()
:O(log n)
wheren
is the decimal value - String operations (
upper()
,replace()
):O(k)
wherek
is the length of the hex string, which isO(log n)
- Checking all characters in set:
O(k)
wherek
is the length of the hex string - Since the hex representation has length proportional to
log n
, the overall time complexity isO(log n)
Space Complexity: O(log n)
- Creating set
s
:O(1)
as it contains a fixed number of characters - Storing hex string
t
:O(log n)
as the hexadecimal representation requiresO(log n)
characters - The
all()
function with generator expression:O(1)
additional space - Overall space complexity is
O(log n)
due to the hex string storage
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Incorrect Order of Operations with String Replacements
A common mistake is performing the replacements before converting to uppercase, or assuming the order of replacements doesn't matter.
Pitfall Example:
# Wrong approach - converting to uppercase after replacements
hex_string = hex(int(num))[2:]
hex_string = hex_string.replace('0', 'O').replace('1', 'I')
hex_string = hex_string.upper() # This won't work correctly!
Why it fails: If you replace '0' with 'O' and '1' with 'I' before converting to uppercase, and the original hex has lowercase letters like 'a', 'b', etc., the final uppercase conversion won't affect the already-replaced 'O' and 'I', but the issue is that you might accidentally replace lowercase 'o' or 'i' if they existed in the intermediate string.
Correct Solution: Always convert to uppercase first, then perform replacements:
hex_string = hex(int(num))[2:].upper()
hex_string = hex_string.replace('0', 'O').replace('1', 'I')
2. Forgetting to Handle Large Numbers
Pitfall Example:
# Attempting to use format strings or other methods that might have limitations
hex_string = format(int(num), 'X') # This works but be aware of potential issues
Why it matters: While Python handles arbitrarily large integers well, it's important to ensure your conversion method works for very large decimal numbers. The hex()
function handles this correctly, but some alternative approaches might have limitations.
Correct Solution: Stick with hex(int(num))
which handles large numbers properly:
# This works for any size number
hex_string = hex(int(num))[2:].upper()
3. Misunderstanding Valid Character Set
Pitfall Example:
# Wrong - forgetting that after replacement, only certain characters are valid
valid_chars = set('0123456789ABCDEF') # This includes all hex digits!
Why it fails: The problem specifically states that after replacements, only letters A-F, I, and O are valid. Digits 2-9 make the result invalid.
Correct Solution: Define the valid set as only the allowed letters after transformation:
valid_chars = set('ABCDEFIO')
4. Not Handling the '0x' Prefix Correctly
Pitfall Example:
# Forgetting to remove the '0x' prefix
hex_string = hex(int(num)).upper() # Results in '0X...' being processed
Why it fails: The hex()
function returns a string starting with '0x' (or '0X' after uppercase). If you don't remove this prefix, the '0' will be incorrectly replaced with 'O', and 'X' will be considered as part of your hexadecimal string.
Correct Solution: Always slice from index 2:
hex_string = hex(int(num))[2:].upper()
Which of the following is a good use case for backtracking?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!