Sobes.tech
Middle+

List<Integer> getNonUnique(int[] one, int[] two) { Map<Integer, Integer> freqOne = new HashMap<>(); Map<Integer, Integer> freqTwo = new HashMap<>(); for (int num : one) { freqOne.put(num, freqOne.getOrDefault(num, 0) + 1); } for (int num : two) { freqTwo.put(num, freqTwo.getOrDefault(num, 0) + 1); } List<Integer> result = new ArrayList<>(); for (Integer key : freqOne.keySet()){ if (freqTwo.containsKey(key)) { result.add(key); } } return result; } //one [phone] //two 3 9 8 1 // result 1 3 //one [phone] //two 3 9 8 1 3 // result 1 3 3

sobes.tech AI

Answer from AI

This method getNonUnique finds common elements between two arrays one and two, considering the number of repetitions in the second array.

Algorithm:

  • Count the frequency of each number in the first array freqOne.
  • Count the frequency of each number in the second array freqTwo.
  • Iterate over the keys in freqOne and if the key exists in freqTwo, add it to the result.

However, in the current implementation, only one instance of each common number is added, which does not match the example with repetitions (for example, for two = [3,9,8,1,3], the result should contain two 3s).

To fix this and get a result with repetitions, you need to add the number to the result as many times as it appears in the second array:

List<Integer> getNonUnique(int[] one, int[] two) {
    Map<Integer, Integer> freqOne = new HashMap<>();
    Map<Integer, Integer> freqTwo = new HashMap<>();

    for (int num : one) {
        freqOne.put(num, freqOne.getOrDefault(num, 0) + 1);
    }

    for (int num : two) {
        freqTwo.put(num, freqTwo.getOrDefault(num, 0) + 1);
    }

    List<Integer> result = new ArrayList<>();
    for (Integer key : freqOne.keySet()) {
        if (freqTwo.containsKey(key)) {
            int count = freqTwo.get(key);
            for (int i = 0; i < count; i++) {
                result.add(key);
            }
        }
    }
    return result;
}

Thus, the method returns a list of numbers from the second array that are also in the first, considering the number of repetitions in the second array.