Given an array arr[] of size N and a string S, the task is to modify given array by removing all characters from their hexadecimal representations that are present in S and then replacing the equivalent decimal element back into the array.
Examples:
Input: arr[] = {74, 91, 31, 122}, S = “1AB”
Output: {4, 5, 15, 7}
Explanation:
74 -> (4A)16 -> (4)16 -> 4
91 -> (5B)16 -> (5)16 -> 5
31 -> (1F)16 -> (F)16 -> 15
122 -> (7A)16 -> (7)16 -> 7Input: arr[] = {1450, 1716, 284, 843}, S = “ABFE3”
Output: {5, 100, 284, 4}
Approach: Follow the steps below to solve the problem:
- Traverse the array arr[]:
- Convert each array element to its equivalent hexadecimal value.
- Remove the characters from the hexadecimal number which are present in the string S.
- Convert the modified hexadecimal number back to its decimal representation.
- Replace the array element with it.
- Print the modified array.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approach # Function to convert a decimal number # to its equivalent hexadecimal number def decHex(n): alpha = ['A', 'B', 'C', 'D', 'E', 'F'] ans = '' while n: if n % 16 < 10: ans += str(n % 16) else: ans += alpha[n % 16 - 10] n //= 16 ans = ans[::-1] return ans # Function to convert hexadecimal number # to its equavalent decimal number def hexDec(convertedHex): # Stores characters with their # respective hexadecimal values mp = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15} # Stores answer ans = 0 pos = 0 # Traverse the string for i in convertedHex[::-1]: # If digit if i.isdigit(): ans += (16**pos)*int(i) # If character else: ans += (16**pos)*mp[i] pos += 1 # Return the answer return ans # Function to move all the # alphabets to front def removeChars(hexaVal, S): setk = set() for i in S: setk.add(i) ans = '' for i in hexaVal: if i in setk: continue ans += i return ans # Function to modify each array # element by removing characters # from their hexadecimal representation # which are present in a given string def convertArr(arr, S): # Traverse the array for i in range(len(arr)): # Stores hexadecimal value hexaVal = decHex(arr[i]) # Remove the characters from hexadecimal # representation present in string S convertedHex = removeChars(hexaVal, S) # Stores decimal value decVal = hexDec(convertedHex) # Replace array element arr[i] = decVal # Print the modified array print(arr) # Driver Code # Given array arr = [74, 91, 31, 122] # Given string S = "1AB" # Function call to modify # array by given operations convertArr(arr, S) |
[4, 5, 15, 7]
Time Complexity: O(N * |S|)
Auxiliary Space: O(|S|)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

