Counting Elements
The problem is asking to count how many elements x
in the given array have a corresponding x + 1
also in the array. Duplicates are counted separately.
Here’s a stepbystep approach to solving this problem:
Create a Set of the Array Elements: We can use a set to keep track of the unique values present in the array. This will help us quickly check whether
x + 1
is present for a givenx
.Iterate Through the Array and Count Elements: We’ll iterate through the original array and check whether
x + 1
is present in the set for each elementx
. If it is present, we increment our count.Return the Count: Finally, we return the count of elements that meet the condition.
Here’s the code:


Explanation:
 The set
unique_elements
helps us quickly determine whetherx + 1
is present for any givenx
in the array.  By iterating through the array and checking whether
x + 1
is in the set, we can count the elements that meet the condition.  The use of the set ensures that the lookup time for checking the presence of
x + 1
is (O(1)).
The time complexity of this solution is (O(n)), where (n) is the length of the input array, and the space complexity is also (O(n)).