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
Hash Set Approach VisualizationInput Array: [1, 3, 2, 3, 5, 0]132350Hash Set (Unique Elements)13250Checking Each Element:0โ†’ Looking for 1โœ“Found! Count = 11โ†’ Looking for 2โœ“Found! Count = 22โ†’ Looking for 3โœ“Found! Count = 33โ†’ Looking for 4โœ—Not found5โ†’ Looking for 6โœ—Not foundFinal ResultCount = 3
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!
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
38.2K Views
Medium Frequency
~15 min Avg. Time
1.5K 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