Skip to content

Counting Elements – LeetCode challenge JavaScript solution

Written on 9th Apr 2020

Counting Elements Problem statement:

LeetCode

Given an integer array 

arr
, count element 
x
 such that 
x + 1
 is also in 
arr
.

If there’re duplicates in 

arr
, count them separately.

Example 1:

Input:

Example 2:

Input:

Example 3:

Input:

Example 4:

Input:

Constraints:

  • 1 <= arr.length <= 1000
  • 0 <= arr[i] <= 1000

Counting Elements ES6 solution

/**
 * @param {number[]} arr
 * @return {number}
 */
var countElements = function(arr) {
    let count = 0;
    for(let i = 0; i < arr.length; i++){
        if(arr.includes(arr[i]+1))
            count++;
        } 
    }
    return count;
};

Submission Output on LeetCode:

Rajesh-Royal on leetcode.