Check If N and Its Double Exist

easy hash set

Problem

You are given an integer array arr (2 to 500 elements, each value between −1000 and 1000). Decide whether it contains two different indices i and j such that arr[i] = 2 × arr[j] — in other words, some element is exactly the double of another element. Return true if such a pair exists, false otherwise.

Inputarr = [10, 2, 5, 3]
Outputtrue
5 sits at index 2 and its double 10 sits at index 0, so a valid pair of indices exists.

def check_if_exist(arr):
    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;
}
boolean checkIfExist(int[] arr) {
    Set<Integer> seen = new HashSet<>();
    for (int x : arr) {
        if (seen.contains(2 * x) || (x % 2 == 0 && seen.contains(x / 2))) {
            return true;
        }
        seen.add(x);
    }
    return false;
}
bool checkIfExist(vector<int>& arr) {
    unordered_set<int> seen;
    for (int x : arr) {
        if (seen.count(2 * x) || (x % 2 == 0 && seen.count(x / 2))) {
            return true;
        }
        seen.insert(x);
    }
    return false;
}
Time: O(n) Space: O(n)