Counting Elements - Problem
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: If arr = [1, 2, 3], then we have element 1 (and 1 + 1 = 2 exists), and element 2 (and 2 + 1 = 3 exists). So the answer is 2.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [1,2,3]
›
Output:
2
💡 Note:
Element 1 has successor 2 in array, element 2 has successor 3 in array. Element 3 has no successor 4. So count = 2.
Example 2 — With Duplicates
$
Input:
arr = [1,1,3,3,5,5,7,7]
›
Output:
0
💡 Note:
No element x has x+1 in the array. 1→2 (missing), 3→4 (missing), 5→6 (missing), 7→8 (missing). Count = 0.
Example 3 — Counting Duplicates
$
Input:
arr = [1,3,2,3,5,0]
›
Output:
3
💡 Note:
Element 0 has successor 1, element 1 has successor 2, element 2 has successor 3. Both instances of 3 don't have successor 4. Count = 3.
Constraints
- 1 ≤ arr.length ≤ 1000
- 0 ≤ arr[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with elements to check for successors
2
Find Successors
For each element x, check if x+1 exists
3
Count Result
Total count of elements with successors
Key Takeaway
🎯 Key Insight: Use hash set to check if x+1 exists in O(1) time instead of scanning the array
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code