For an array of numbers arr and a number k, return a new array whose number of repeated elements does not exceed k. Example: Input: arr=[1,1,1,2,3,3,3,4,4], k=3 Output: res=[1,3,4]
sobes.tech AI
Answer from AI
To obtain a new array where the number of repeated elements does not exceed k, you need to filter the original array, leaving only those elements that occur no more than k times.
Example solution in Java:
import java.util.*;
public class FilterArray {
public static List<Integer> filterByFrequency(int[] arr, int k) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
if (entry.getValue() <= k) {
result.add(entry.getKey());
}
}
return result;
}
public static void main(String[] args) {
int[] arr = {1,1,1,2,3,3,3,4,4};
int k = 3;
List<Integer> res = filterByFrequency(arr, k);
System.out.println(res); // Outputs [2, 4]
}
}
In your example, Output: [1,3,4] — this means that elements with a number of repetitions not more than k=3 are retained. In the array, 1 occurs 3 times, 3 — 3 times, 4 — 2 times, 2 — 1 time. If you need to return elements that occur exactly k times, the condition changes.
If you want to return elements that occur exactly k times, then use entry.getValue() == k.
If you want to return elements that occur at least k times, then use entry.getValue() >= k.
In your example, to get [1,3,4], you need to return elements that occur at least k=2 times, for example:
if (entry.getValue() >= 2) {
result.add(entry.getKey());
}
Please clarify the exact condition if you need a different behavior.