Check If N and Its Double Exist

This solution creates a set to keep track of the numbers encountered so far, then for each number, it checks if its double or its half (if the number is even) is present in the set.

Python solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def checkIfExist(self, arr: List[int]) -> bool:
        # create an empty set
        seen = set()

        # iterate over each number in arr
        for num in arr:
            # check if double of num or half of num is present in seen
            if 2 * num in seen or (num % 2 == 0 and num // 2 in seen):
                return True
            # if not, add num to seen
            seen.add(num)

        # if we have not returned True by now, no such pair exists
        return False

This algorithm works because it considers each number in arr in order, and for each number, it checks if its double or half is in the set of previously seen numbers. Therefore, if there are any two indices i and j such that arr[i] == 2 * arr[j], this pair will be detected either when considering index i (if i > j) or when considering index j (if j > i). If no such pair exists, we will iterate through the whole array and return False.