Count Elements x and x+1 Present in List in Python

Suppose we have a list of numbers called nums, we have to find the number of elements x there are such that x + 1 exists as well.

So, if the input is like [2, 3, 3, 4, 8], then the output will be 3 because:

  • 2 has 3 (2+1) in the list
  • 3 has 4 (3+1) in the list (counted twice since 3 appears twice)
  • 4 doesn't have 5 in the list
  • 8 doesn't have 9 in the list

Algorithm

To solve this, we will follow these steps ?

  • Create a set from the list for O(1) lookup time
  • Initialize count to 0
  • For each element i in the original list, check if i+1 exists in the set
  • If it exists, increment the count
  • Return the final count

Using Set for Fast Lookup

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, nums):
        s = set(nums)
        count = 0
        for i in nums:
            if i+1 in s:
                count += 1
        return count

ob = Solution()
nums = [2, 3, 3, 4, 8]
print(ob.solve(nums))
3

Alternative Approach Using List Comprehension

We can also solve this problem using a more concise approach with list comprehension ?

def count_consecutive_pairs(nums):
    num_set = set(nums)
    return sum(1 for num in nums if num + 1 in num_set)

nums = [2, 3, 3, 4, 8]
result = count_consecutive_pairs(nums)
print(f"Count of elements with consecutive element present: {result}")
Count of elements with consecutive element present: 3

Step-by-Step Walkthrough

Let's trace through the example [2, 3, 3, 4, 8] ?

nums = [2, 3, 3, 4, 8]
num_set = set(nums)  # {2, 3, 4, 8}

print(f"Original list: {nums}")
print(f"Set for lookup: {num_set}")
print()

count = 0
for i, num in enumerate(nums):
    if num + 1 in num_set:
        count += 1
        print(f"Element {num} at index {i}: {num + 1} exists in set. Count = {count}")
    else:
        print(f"Element {num} at index {i}: {num + 1} does not exist in set.")

print(f"\nFinal count: {count}")
Original list: [2, 3, 3, 4, 8]
Set for lookup: {2, 3, 4, 8}

Element 2 at index 0: 3 exists in set. Count = 1
Element 3 at index 1: 4 exists in set. Count = 2
Element 3 at index 2: 4 exists in set. Count = 3
Element 4 at index 3: 5 does not exist in set.
Element 8 at index 4: 9 does not exist in set.

Final count: 3

Conclusion

The key insight is using a set for O(1) lookup time, making the overall time complexity O(n). This approach counts each occurrence of an element x if x+1 exists in the list, which is why duplicates are counted separately.

---
Updated on: 2026-03-25T10:19:36+05:30

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements