Count array elements whose successor x + 1 is also present
Company: DRW
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
Overview: Count how many entries x of an integer array have x + 1 also present somewhere in the array, with duplicate copies of x counted separately. Tests hash set membership checks and careful reading of how duplicates are counted.
Constraints
- 1 <= arr.length <= 1000
- 0 <= arr[i] <= 1000
- arr may contain duplicates and need not be sorted
Examples
Input: ([1, 2, 3],)
Expected Output: 2
Explanation: Source example 1: 1 and 2 count because 2 and 3 are present, and 3 has no 4.
Input: ([1, 1, 3, 3, 5, 5, 7, 7],)
Expected Output: 0
Explanation: Source example 2: values separated by gaps of two, and none of 2, 4, 6 or 8 is present.
Hints
- Each position is judged on its own, so two copies of the same x can both count.
- Whether x counts depends only on whether the value x + 1 occurs at least once somewhere in the array. Its number of copies and its position play no part.
- Check your reasoning on [1, 1, 2, 2]: the answer is 2.