Given an integer N, and the string integer M, the task is to find the total count to make N by using the digits of string M. Also, digit 2 can be treated as digit 5, and digit 6 can be treated as digit 9 and vice versa and each digit from the string M can be used at most once.
Examples:
Input: N = 6, M = "245769"
Output: 2
Explanation: Digits 5 and 6 are used to form the number 56. iop[The digits 2 and 9 are used to form the number 56. As 2 is treated as 5 and 9 is treated as 6.
Input: N = 25, M = "55"
Output: 1
Approach: The given problem can be solved by Hashing. Follow the steps below to solve the problem:
- Create an empty hashmap, say map to store the frequency of the digits of the given string M.
- Create a variable, say, len to store the length of the string.
- Traverse the given string S using the variable i and Iterate until the value of i is less than len and perform the following steps:
- If the character S[i] is equal to '5', then change it to '2'.
- If the character S[i] is equal to '9', then change it to '6'.
- If the character is present in the mymap, then change the frequency as mymap.put(x, map.get(x)+1).
- Otherwise, insert the character in the map with frequency 1 as mymap.put(x, 1).
- After adding the frequency to the map, increment i and continue to the next iteration.
- Create an empty hashmap, say rems to store the digits of the number N.
- Iterate until the value of N is greater than 0, and perform the following steps:
- Create a variable, say rem to store the last digit of N by using the modulus operator as N%10.
- If rem is equal to 5, then change it to 2.
- If rem is equal to 9, then change it to 6.
- If the rem is present in the rems map, then increase the frequency by 1as rems.put(rem, rems.get(rem)+1).
- Otherwise, insert it to the rems map as rems.put(rem, 1).
- Divide N by 10.
- Create a variable, say cnt to store the maximum count of the number N that can be formed using the given digits of string M.
- Traverse through the map rems, and perform the following steps:
- Let each object in the map is ele.
- Check if the key from ele is present in the frequency map of string mymap.
- If not present, the return 0 (The number N cannot be formed if a digit from N is not present in string M).
- Calculate the count by dividing the frequency of the key in mymap with the frequency in rems map as mymap.get(key)/ele.getValue().
- Update the minimum value from all iterations in cnt.
- After completing the above steps, print the value of cnt as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)