Approach: To solve this question, store the frequencies of each number in a map and then create a custom comparator, which will do the sorting. That compare function will accept two integer values, say A and B as parameters and the condition in that comparator to sort the array is:
(A % frequency(A)) > (B % frequency(B))
Create an unordered map to store the frequencies of each number in the array.
Sort the array using a custom comparator that compares the modulus of the values of two elements in the array with their respective frequencies.
If the modulus is the same, compare the values of the elements and return true if the first element is smaller than the second element.
If the modulus is not the same, compare the modulus of the two elements and return true if the modulus of the first element is smaller than the modulus of the second element.
Print the sorted array.
freq_map = empty unordered map
for element in array:
increment the frequency of element in freq_map
sort array using a custom comparator:
if modulus of A with freq[A] is equal to modulus of B with freq[B]:
return A < B
return modulus of A with freq[A] < modulus of B with freq[B]
print the sorted array
Below is the implementation of the above approach.
Please Login to comment...