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


Suppose we have a list of numbers say nums, we have to find the number of elements x in the array, such that x + 1 also exists in the array.

So, if the input is like nums = [4, 2, 3, 3, 7, 9], then the output will be 3, because 2+1 = 3 is present, 3+1 = 4 is present and another 3 is present so total 3.

To solve this, we will follow these steps −

  • answer := 0

  • c := a list containing frequencies of each elements present in nums

  • dlist := a list from list of all keys of c

  • for each i in dlist, do

    • if c[i + 1] > 0, then

      • answer := answer + c[i]

  • return answer

Example

Let us see the following implementation to get better understanding

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]
print(solve(nums))

Input

[4, 2, 3, 3, 7, 9]

Output

3

Updated on: 11-Oct-2021

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements