![]() |
VOOZH | about |
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the array elements having frequencies in the power of K i.e., K1, K2, K3, and so on.
Examples:
Input: arr[] = {1, 3, 2, 1, 2, 2, 2, 3, 3, 4}, K = 2
Output: 1 2
Explanation:
The frequency of 1 is 2, that can be represented as the power of K( = 2), i.e., 21.
The frequency of 2 is 4, that can be represented as the power of K( = 2), i.e., 22.Input: arr[] = {6, 1, 3, 1, 2, 2, 1}, K = 2
Output: 2 3 6
Naive Approach: The simplest approach is to count the frequencies of each array element and if the frequency of any element is a perfect power of K, then print that element. Otherwise, check for the next element.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using Hashing for storing the frequency of arrays elements in a HashMap and then check for the required conditions. Follow the steps below to solve the given problem:
Below is the implementation of the above approach:
3 2 1 4
Time Complexity: O(N)
Auxiliary Space: O(N)