Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7301bc3

Browse files
committed
Counting the elements for an array where the next element is also present in the array
1 parent 3f5a936 commit 7301bc3

File tree

7 files changed

+38
-0
lines changed

7 files changed

+38
-0
lines changed
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
3+
Given an integer array arr, count element x such that x + 1 is also in arr.
4+
If there’re duplicates in arr, count them seperately.
5+
6+
Example 1:
7+
Input: arr = [1,2,3]
8+
Output: 2
9+
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
10+
11+
Example 2:
12+
Input: arr = [1,1,3,3,5,5,7,7]
13+
Output: 0
14+
Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.
15+
16+
Example 3:
17+
Input: arr = [1,3,2,3,5,0]
18+
Output: 3
19+
Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
20+
21+
Example 4:
22+
Input: arr = [1,1,2,2]
23+
Output: 2
24+
Explanation: Two 1s are counted cause 2 is in arr.
25+
26+
Constraints:
27+
1 <= arr.length <= 1000
28+
0 <= arr[i] <= 1000
29+
30+
*/
31+
32+
export const countElements = (nums) => {
33+
const lookup = new Set(nums);
34+
return nums.reduce(
35+
(count, val) => (lookup.has(val + 1) ? count + 1 : count),
36+
0
37+
);
38+
};

0 commit comments

Comments
 (0)