Check If N and Its Double Exist Problem
Description
LeetCode Problem 1346.
Given an array arr of integers, check if there exist two indices i and j such that :
i != j0 <= i, j < arr.lengtharr[i] == 2 * arr[j]
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]
Example 2:
Input: arr = [3,1,7,11]
Output: false
Explanation: There is no i and j that satisfy the conditions.
Constraints:
2 <= arr.length <= 500-10^3 <= arr[i] <= 10^3
Solution
Approach: Hash Set
Walk through the array and keep a set of the numbers seen so far. For each number x, an earlier partner exists if the set contains 2 * x (an earlier number is the double of x) or, when x is even, x / 2 (x is the double of an earlier number). If so, return true; otherwise add x and continue.
Checking both directions matters because the partner may come before or after x: whichever of the two comes second finds the other in the set. Only even numbers can be a double, which avoids matching 3 with 1 by rounding 3 / 2 down.
The rule i != j is the tricky case with 0, since 0 = 2 * 0. Because x is looked up before it is added, a single 0 never matches itself, while two zeros do.
Complexity: O(n) time and O(n) extra space.
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
seen = set() # the numbers before the current one
for x in arr:
# x pairs with an earlier number that is its double or its half.
if 2 * x in seen or (x % 2 == 0 and x // 2 in seen):
return True
seen.add(x)
return False