Counting Elements - Problem
๐ข Counting Elements
You are given an integer array arr and need to find how many elements x exist such that x + 1 is also present in the array.
The key insight is that we're looking for consecutive integer pairs where both numbers exist in the array. If an element appears multiple times, each occurrence should be counted separately.
Example: In array [1, 2, 3], we have:
- 1 โ 1+1=2 exists โ
- 2 โ 2+1=3 exists โ
- 3 โ 3+1=4 doesn't exist โ
So the answer is 2.
Goal: Return the count of elements that have their immediate successor in the array.
Input & Output
example_1.py โ Basic Case
$
Input:
[1, 2, 3]
โบ
Output:
2
๐ก Note:
Elements 1 and 2 have their successors (2 and 3) in the array. Element 3 doesn't have 4, so count is 2.
example_2.py โ With Duplicates
$
Input:
[1, 1, 3, 3, 5, 5, 7, 7]
โบ
Output:
0
๐ก Note:
None of the elements have their immediate successor. No element x has x+1 in the array, so count is 0.
example_3.py โ Mixed Duplicates
$
Input:
[1, 3, 2, 3, 5, 0]
โบ
Output:
3
๐ก Note:
Element 0โ1 exists โ, element 1โ2 exists โ, element 2โ3 exists โ. Other elements don't have successors. Count = 3.
Constraints
- 0 โค arr.length โค 1000
- 0 โค arr[i] โค 1000
- Array elements can be duplicated
- Empty array should return 0
Visualization
Tap to expand
Understanding the Visualization
1
Create Quick Lookup
Build a hash set (like a phone book) of all people in the group for instant lookups
2
Check Each Person
For each person with ID x, quickly check if person with ID x+1 exists in our phone book
3
Count the Connections
Every time we find someone whose next friend exists, increment our counter
Key Takeaway
๐ฏ Key Insight: Hash sets transform expensive O(nยฒ) searches into O(1) lookups, making the solution linear time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code