The problem asks to count the number of elements x
in an array arr
such that x + 1
is also present in arr
. Duplicate elements should be counted individually.
Approach:
The most efficient approach uses a hash map (or an array if the input values are within a known range) to store the frequency of each element in the array. Then, we iterate through the unique elements and check if x + 1
exists in the hash map. If it does, we add the count of x
to the final answer.
Time Complexity Analysis:
arr
. We iterate through the array once.x + 1
also takes O(m) time, where m is the number of unique elements in the array. In the worst case, m could be n (if all elements are unique).Therefore, the overall time complexity is O(n) in the average case, and O(n) in the worst case (when all elements are unique).
Space Complexity Analysis:
The space complexity is dominated by the space used to store the frequency map. In the worst case (all unique elements), this requires O(n) space. If the input numbers are within a known range (like in the example solutions using an array of size 1001), the space complexity becomes O(1).
Code Implementation (Python):
from collections import Counter
class Solution:
def countElements(self, arr: List[int]) -> int:
count = Counter(arr) # Creates a frequency map (dictionary)
ans = 0
for x in count:
if x + 1 in count:
ans += count[x]
return ans
This Python code uses the Counter
object from the collections
module for efficient frequency counting. It iterates through the unique elements in the count
dictionary and checks for the presence of x + 1
.
Code Implementation (Java):
import java.util.HashMap;
import java.util.Map;
class Solution {
public int countElements(int[] arr) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : arr) {
count.put(x, count.getOrDefault(x, 0) + 1);
}
int ans = 0;
for (int x : count.keySet()) {
if (count.containsKey(x + 1)) {
ans += count.get(x);
}
}
return ans;
}
}
The Java code uses a HashMap
to store the frequencies. It iterates through the keys of the HashMap
and checks for the existence of x + 1
. The getOrDefault
method handles cases where a key might not exist.
The other language implementations follow similar logic, adapting the data structures and syntax as needed for the specific language. The core idea of using a frequency map and then iterating to check for x + 1
remains consistent across all solutions.