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 }
13 iterated.add(num)
14 }
15
16 return existed
17}

Comments

Loading comments...

Tags

leetcode

array

hash table

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Valid Mountain Array

Jul 25, 2021

Flagging

Previous Post

LeetCode: Palindrome Number

Jul 22, 2021

Split, reverse, join

HoningJS

Search Posts