![]() |
VOOZH | about |
Given a range [L, R]. The task is to find the total number of Hexadecimal alphabets that are required to write every number in the range.
Hexadecimal alphabets are the alphabets in the range [A, F] that are required to represent decimal numbers from the range [10, 15]
Examples:
Input: L = 10, R = 15
Output: 6
All the numbers from 10 to 15 contain a hexadecimal alphabet.Input: L = 15, R = 16
Output: 1
15 and 16 are represented in hexadecimal as F and 10 respectively.
Approach:
Below is the implementation of the above approach:
36
Time Complexity: O(N * log16 N), Here N is the range (R - L) and for every number, we need log16 N time to calculate the number of hexadecimal alphabets.
Auxiliary Space: O(1), As constant extra space is used.
1. This method uses a set intersection operation to check if the hexadecimal characters are present in the hexadecimal string of each number in the range.
2. It initializes a set of hexadecimal characters and loops through each number in the range.
3. It then computes the hexadecimal string of the number using the built-in hex function and removes the '0x' prefix using string slicing.
4. It checks if the intersection of the set of hexadecimal characters and the set of characters in the hexadecimal string is non-empty, indicating the presence of a hexadecimal character. If the intersection is non-empty, the count is incremented.
6
Time complexity: O((R-L+1) * k), where k is the length of the maximum hexadecimal string in the range.
The reason for this is that the method loops through each number in the range (R-L+1 numbers), computes its hexadecimal string using the built-in hex function (which takes time proportional to the number of digits in the hexadecimal representation), removes the '0x' prefix using string slicing (which takes constant time), and checks if the intersection of the set of hexadecimal characters and the set of characters in the hexadecimal string is non-empty using the & operator (which takes time proportional to the length of the sets being intersected). The maximum length of the hexadecimal string is k, which is log base 16 of the maximum number in the range.
Auxiliary space: O(k), since it creates a set of hexadecimal characters with constant size and potentially creates a set of characters in the hexadecimal string for each number in the range with maximum size k. However, since k is a fixed constant, the space complexity is considered O(1) in practice.