### Problem

Write a javascript function:

`function solution(arr);`

that, given an array ** arr** of

**positive integers returns 1 if**

`n`

**contains at least two items which differ by 1 otherwise 0.**

`arr`

#### Examples

- Given,
`arr=[9]`

, the method should return`0`

. - Given,
`arr=[5,4]`

, the method should return`1`

. - Given,
`arr=[12, 2, 9, 13, 15]`

, the method should return`1`

. Pair of items which differ by 1 is`(12, 13)`

. - Given,
`arr=[5, 11, 9, 6, 10]`

, the method should return`1`

. Pairs of items which differ by 1 are`(5, 6)`

,`(11, 10)`

and`(8, 9)`

. - Given,
`arr=[6, 6, 6, 6, 6]`

, the method should return`0`

. There are no two items in array whose values differ by 1.

Write an algorithm for the following consideration

`n is a positive integer in the range of 1..,99,999].`

`each items of an array is a positive integer in the range 1...99,99,99,999]`

### Solution

```
function solution(arr) {
if (arr && arr.length > 0) {
let visitedNum = new Set();
let result = arr.every((num) => {
if (visitedNum.has(num - 1) || visitedNum.has(num + 1)) {
return 0;
}
visitedNum.add(num);
return 1;
});
return !result;
}
return 0;
}
```

The solution above is pretty self-explanatory.

### Result

Runtime | Memory |
---|---|

80 ms | 24.6 MB |

💌 If you’d like to receive more coding solutions in your inbox, you can sign up for the newsletter here.

## Discussions