- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

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

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

3

- Related Questions & Answers
- Elements greater than the previous and next element in an Array in C++
- Python Program to find the Next Nearest element in a Matrix
- Count number of subsets whose median is also present in the same subset in C++
- Program to find smallest index for which array element is also same as index in Python
- Python program to count the elements in a list until an element is a Tuple?
- Next Greater Element in Circular Array in JavaScript
- Count distinct elements in an array in Python
- Program to count index pairs for which array elements are same in Python
- Find next sibling element in Selenium, Python?
- Program to count number of paths whose sum is k in python
- Count pairs whose products exist in array in C++
- Count frequencies of all elements in array in Python
- Python Program to find the largest element in an array
- Write a Java program to find the first array element whose value is repeated an integer array?
- Python Program to Count Inversions in an array

Advertisements