Counting Elements Problem
#1426
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1426.
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.
Example 1:
Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
Example 2:
Input: arr = [1,1,3,3,5,5,7,7]
Output: 0
Explanation: No numbers are counted, cause there is no 2, 4, 6, or 8 in arr.
Constraints:
1 <= arr.length <= 10000 <= arr[i] <= 1000
Solution
Approach: Hash Set
Put every value in a hash set, then walk through arr and count the elements x for which x + 1 is in the set.
The one thing to get right is duplicates: they are counted separately, so in [1, 1, 2] the answer is 2. That is why the counting loop goes over arr itself, not over the set of distinct values. (Duplicates of x + 1 do not matter, it only has to be present.)
Complexity: O(n) time and O(n) extra space.
class Solution:
def countElements(self, arr: List[int]) -> int:
present = set(arr)
# duplicates are counted separately, so loop over arr, not over the set
return sum(1 for x in arr if x + 1 in present)