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
Counting Elements - Hash Set Lookup INPUT arr = [1, 2, 3] 1 index 0 2 index 1 3 index 2 Hash Set Created: {1, 2, 3} Store all elements for O(1) lookup For each x, check if (x + 1) exists in set ALGORITHM STEPS 1 Build Hash Set Add all elements to set 2 Initialize count = 0 Counter for valid elements 3 For each x in arr: Check if (x+1) in set 4 Increment count If found, count++ Execution Trace: x x+1 In Set? Count 1 2 YES 1 2 3 YES 2 3 4 NO 2 FINAL RESULT Elements where x+1 exists: 1 1+1=2 OK 2 2+1=3 OK 3 3+1=4 NOT in set Output: 2 2 elements found where (x + 1) exists in array Key Insight: Using a Hash Set allows O(1) lookup time to check if (x + 1) exists in the array. This reduces the overall time complexity from O(n^2) brute force to O(n). Duplicates are counted separately since we iterate through the original array, not the set. TutorialsPoint - Counting Elements | Hash Set Lookup Approach
Asked in
Facebook 15 Amazon 12
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen