Count array elements whose successor x + 1 is also present

Quick 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.

Count array elements whose successor x + 1 is also present

Company: DRW

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

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. ### Function Signature ```python def count_elements(arr: list[int]) -> int: ``` ### Rules - Every position of `arr` is checked on its own. An element `x` adds one to the count for each time it appears, as long as `x + 1` appears at least once anywhere in `arr`. - The number of copies of `x + 1` does not matter. Extra copies of `x + 1` do not add extra counts for `x`. ### Constraints - `1 <= arr.length <= 1000` - `0 <= arr[i] <= 1000` ### Examples ```text Input: arr = [1,2,3] Output: 2 ``` 1 and 2 are counted because 2 and 3 are in `arr`. 3 is not counted because there is no 4. ```text Input: arr = [1,1,3,3,5,5,7,7] Output: 0 ``` No numbers are counted, because there is no 2, 4, 6 or 8 in `arr`. ```text Input: arr = [1,1,2,2] Output: 2 ``` Both copies of 1 are counted because 2 is present. Neither copy of 2 is counted because 3 is absent, and the second copy of 2 does not count either 1 a second time.

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.

DRW logo
DRW
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

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.

Function Signature

def count_elements(arr: list[int]) -> int:

Rules

  • Every position of arr is checked on its own. An element x adds one to the count for each time it appears, as long as x + 1 appears at least once anywhere in arr .
  • The number of copies of x + 1 does not matter. Extra copies of x + 1 do not add extra counts for x .

Constraints

  • 1 <= arr.length <= 1000
  • 0 <= arr[i] <= 1000

Examples

Input: arr = [1,2,3]
Output: 2

1 and 2 are counted because 2 and 3 are in arr. 3 is not counted because there is no 4.

Input: arr = [1,1,3,3,5,5,7,7]
Output: 0

No numbers are counted, because there is no 2, 4, 6 or 8 in arr.

Input: arr = [1,1,2,2]
Output: 2

Both copies of 1 are counted because 2 is present. Neither copy of 2 is counted because 3 is absent, and the second copy of 2 does not count either 1 a second time.