LeetCode 1426: Counting Elements

ArrayHash Table

Problem Description

Explanation:

This problem asks us to find the number of elements in an array that are present in the array but have a count of 'count+1'. We can achieve this by counting the frequency of each element in the array and then checking if the count of 'element+1' is greater than 0.

Algorithmic Steps:

  1. Create a HashMap to store the frequency of each element in the array.
  2. Iterate through the array and populate the HashMap with the frequency of each element.
  3. Iterate through the HashMap, and for each key 'num', check if 'num+1' exists in the HashMap. If it does, increment the result by the frequency of 'num'.

Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n) for the HashMap.

:

Solutions

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int countElements(int[] arr) {
        Map<Integer, Integer> freqMap = new HashMap<>();
        int result = 0;

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

        for (int num : freqMap.keySet()) {
            if (freqMap.containsKey(num + 1)) {
                result += freqMap.get(num);
            }
        }

        return result;
    }
}

Loading editor...