- Related Questions & Answers
- Difference between x++ and x = x+1 in Java
- Difference between x++ and x= x+1 in Java programming
- Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n in C++
- Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x).
- Differences between Python 2.x and Python 3.x?
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors in C++
- Program to find X for special array with X elements greater than or equal X in Python
- Program to count number of ways we can fill 3 x n box with 2 x 1 dominos in Python
- Count elements such that there are exactly X elements with values greater than or equal to X in C++
- Important differences between Python 2.x and Python 3.x with examples
- Sqrt(x) in Python
- What are the differences in between python 2.x and python 3.x versions?
- Maximize the sum of X+Y elements by picking X and Y elements from 1st and 2nd array in C++
- Count of values of x <= n for which (n XOR x) = (n – x) in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

- if i+1 in s, then
- return count

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

[2, 3, 3, 4, 8]

3

Advertisements