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

PythonServer Side ProgrammingProgramming

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

To solve this, we will follow these steps −

  • s := make a set by inserting elements present in nums
  • count := 0
  • for each i in nums, do
    • if i+1 in s, then
      • count := count + 1
  • return count

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

[2, 3, 3, 4, 8]

Output

3
raja
Published on 22-Sep-2020 11:12:23
Advertisements