Program to count elements whose next element also in the array in Python

Given an array of numbers, we need to count how many elements x have their next consecutive number (x + 1) also present in the array. This problem involves frequency counting and checking for consecutive elements.

Problem Understanding

For the input nums = [4, 2, 3, 3, 7, 9], we need to find elements whose next consecutive number exists:

  • Element 2: 2 + 1 = 3 exists in array (count: 1)

  • Element 3: 3 + 1 = 4 exists in array (count: 2, since 3 appears twice)

  • Element 4: 4 + 1 = 5 does not exist

  • Element 7: 7 + 1 = 8 does not exist

  • Element 9: 9 + 1 = 10 does not exist

Total count = 1 + 2 = 3

Solution Using Counter

We use Python's Counter to track element frequencies, then check if each element's successor exists ?

from collections import Counter

def solve(nums):
    answer = 0
    c = Counter(nums)
    dlist = list(c.keys())
    
    for i in dlist:
        if c[i + 1] > 0:
            answer += c[i]
    
    return answer

nums = [4, 2, 3, 3, 7, 9]
result = solve(nums)
print(f"Input: {nums}")
print(f"Output: {result}")
Input: [4, 2, 3, 3, 7, 9]
Output: 3

Alternative Solution Using Set

For cases where we only need to check existence (not frequencies), a set-based approach works efficiently ?

def solve_with_set(nums):
    num_set = set(nums)
    count = 0
    
    for num in nums:
        if num + 1 in num_set:
            count += 1
    
    return count

nums = [4, 2, 3, 3, 7, 9]
result = solve_with_set(nums)
print(f"Input: {nums}")
print(f"Output: {result}")
Output: 3

Step-by-Step Algorithm

  1. Create a frequency counter of all elements in the array

  2. For each unique element x in the array:

    • Check if x + 1 exists in the counter

    • If yes, add the frequency of x to the answer

  3. Return the total count

Comparison

Method Time Complexity Space Complexity Best For
Counter approach O(n) O(n) When duplicates matter
Set approach O(n) O(n) Simple existence check

Conclusion

Use Counter when element frequencies matter, as it properly handles duplicate elements. The set-based approach offers a cleaner solution when only checking for consecutive number existence.

Updated on: 2026-03-26T15:10:57+05:30

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements