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.