For each x, check if 2x or x/2 (when even) already seen.
TimeComplexity:O(n)
SpaceComplexity:O(n)
""" 1346.1 - Check If N and Its Double Exist - Solution 1 - Hash Set """
from typing import List
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
seen = set()
for x in arr:
if 2*x in seen or (x % 2 == 0 and x//2 in seen):
return True
seen.add(x)
return False
function checkIfExist(arr){
const seen=new Set();
for(const x of arr){
if(seen.has(2*x) || (x%2===0 && seen.has(x/2))) return true;
seen.add(x);
}
return false;
}
function checkIfExist(arr:number[]):boolean{
const seen:Set<number>=new Set();
for(const x of arr){
if(seen.has(2*x) || (x%2===0 && seen.has(x/2))) return true;
seen.add(x);
}
return false;
}
package main
func checkIfExist(arr []int) bool {
seen := map[int]bool{}
for _, x := range arr {
if seen[2*x] || (x%2 == 0 && seen[x/2]) {
return true
}
seen[x] = true
}
return false
}
func main() {}
use std::collections::HashSet;
fn check_if_exist(arr: &[i32]) -> bool {
let mut seen: HashSet<i32> = HashSet::new();
for &x in arr {
if seen.contains(&(2*x)) || (x%2==0 && seen.contains(&(x/2))) { return true; }
seen.insert(x);
}
false
}
fn main() {}