Problem Description
Given an integer array arr, count how many elements x there are such that x + 1 is also present in arr. Duplicates in arr are counted separately.
Key Insights
- Use a hash table or set to store unique elements from arr for constant time lookups.
- Iterate through each element in arr and check if x + 1 exists in the set.
- Count each valid occurrence, including duplicates.
- This approach efficiently handles the problem without needing nested loops.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in arr (set lookups are O(1) on average).
Space Complexity: O(n), due to the use of an auxiliary set to store unique elements.
Solution
The solution leverages a set to achieve constant time membership checks. First, we convert arr to a set of unique numbers. Then, iterate through arr, and for each element, check if (element + 1) exists in the set. If it does, increment the count. This approach correctly handles duplicates by counting each occurrence during iteration.