Skip to content

1426. Counting Elements

  • Time: $O(n)$
  • Space: $O(n)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  int countElements(vector<int>& arr) {
    unordered_set<int> arrSet{arr.begin(), arr.end()};
    return ranges::count_if(
        arr, [&arrSet](int a) { return arrSet.contains(a + 1); });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int countElements(int[] arr) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int a : arr)
      count.merge(a, 1, Integer::sum);

    for (Map.Entry<Integer, Integer> entry : count.entrySet())
      if (count.containsKey(entry.getKey() + 1))
        ans += entry.getValue();

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def countElements(self, arr: list[int]) -> int:
    count = collections.Counter(arr)
    return sum(freq
               for a, freq in count.items()
               if count[a + 1] > 0)