#1426
Easy Algorithms Counting elements
Array Hash Table
60.8% acceptance
Mar 31, 2026
168
66
Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. If there are duplicates in arr, count them separately.
Solution
Rust
Time O(n)
Space O(1)
use std::collections::HashSet;
impl Solution {
pub fn count_elements(arr: Vec<i32>) -> i32 {
let set: HashSet<i32> = arr.iter().copied().collect();
arr.iter().filter(|&&x| set.contains(&(x + 1))).count() as i32
}
}