# LeetCode: Check If N and Its Double Exist Solution

Compare with the iterated elements

## Approach

Nested loop: for every element, check with other elements

Hash table: save a loop by using a hash table of the checked elements

## Implementation (nested loop)

1/**
2 * @param {number[]} arr
3 * @return {boolean}
4 */
5var checkIfExist = function (arr) {
6 let existed = false
7
8 for (let i = 0; i < arr.length; i++) {
9 for (let j = 0; j < arr.length; j++) {
10 if (i !== j && (arr[i] === 2 * arr[j] || arr[j] === 2 * arr[i])) {
11 existed = true
12 }
13 }
14 }
15
16 return existed
17}

## Implementation (hash table)

1/**
2 * @param {number[]} arr
3 * @return {boolean}
4 */
5var checkIfExist = function (arr) {
6 const iterated = new Set()
7 let existed = false
8
9 for (const num of arr) {
10 if (iterated.has(num * 2) || iterated.has(num / 2)) {
11 existed = true
12 }
14 }
15
16 return existed
17}

leetcode

array

hash table

## Next Post

LeetCode: Valid Mountain Array

Jul 25, 2021

Flagging

## Previous Post

LeetCode: Palindrome Number

Jul 22, 2021

Split, reverse, join

Search Posts