LeetCode: Check If N and Its Double Exist Solution
Compare with the iterated elementsApproach
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[]} arr3 * @return {boolean}4 */5var checkIfExist = function (arr) {6 let existed = false78 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 = true12 }13 }14 }1516 return existed17}
Implementation (hash table)
1/**2 * @param {number[]} arr3 * @return {boolean}4 */5var checkIfExist = function (arr) {6 const iterated = new Set()7 let existed = false89 for (const num of arr) {10 if (iterated.has(num * 2) || iterated.has(num / 2)) {11 existed = true12 }13 iterated.add(num)14 }1516 return existed17}
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.