Code Logo

Counting Elements

Published at24 Jul 2026
Easy 0 views
Like0

Given an integer array, count how many numbers x have x + 1 also present in the array. Each occurrence counts separately — if a number appears multiple times, each appearance where its successor exists adds 1 to the total.

A brute force approach would check each element against every other element in O(n²) time. Using a hash set reduces this to O(n) by storing all numbers for O(1) lookups. Simply iterate the array, and for each element, check if element + 1 is in the set. Count the number of elements that satisfy this condition.

This problem is a warm-up to using hash sets for existence queries. The key insight is that we only need to check forward (x + 1), not backward. Each element is evaluated independently, and duplicates in the array count separately.

Edge cases include an empty array (return 0), an array with a single element (return 0 since x+1 cannot exist), and an array where every element has its successor (e.g., [1,2,3] counts 2 for 1→2 and 2→3).

Using a hash set instead of a hash map is sufficient here because we only need to know if x+1 exists, not how many times it appears. Each occurrence of x contributes independently to the count, so we iterate the original array rather than the set. This approach works for up to 10^5 elements comfortably.

Example Input & Output

Example 1
Input
[1,1,2,2]
Output
2
Explanation

First 1 counts (2 exists), second 1 also counts.

Example 2
Input
[1,1,2]
Output
2
Explanation

Both 1s count since 2 exists.

Example 3
Input
[1,1,3,3,5,5,7,7]
Output
0
Explanation

No number has its successor.

Example 4
Input
[]
Output
0
Explanation

Empty.

Example 5
Input
[1,2,3]
Output
2
Explanation

1+1=2 exists, 2+1=3 exists. 3+1=4 does not.

Algorithm Flow

Recommendation Algorithm Flow for Counting Elements
Recommendation Algorithm Flow for Counting Elements

Solution Approach

Insert all numbers into a hash set. Iterate the array counting elements whose successor is in the set.

function solution(nums) {
  var s = {};
  for (var i = 0; i < nums.length; i++) s[nums[i]] = true;
  var count = 0;
  for (var i = 0; i < nums.length; i++) {
    if (s[nums[i] + 1]) count++;
  }
  return count;
}

Time O(n), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(int[] nums) {
        Set<Integer> s = new HashSet<>();
        for (int n : nums) s.add(n);
        int count = 0;
        for (int n : nums) {
            if (s.contains(n + 1)) count++;
        }
        return count;
    }
}