Check If N and Its Double Exist — Binary Search or Hash Set
Advertisement
Problem 307 · Check If N and Its Double Exist
Difficulty: Easy · Pattern: Hash Set / Binary Search
Solutions
# Python — O(n) hash set
def checkIfExist(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
// Java
public 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;
}
# Python — sorting + binary search
import bisect
def checkIfExist(arr):
arr.sort()
n = len(arr)
for i, x in enumerate(arr):
target = 2*x
j = bisect.bisect_left(arr, target)
if j < n and arr[j] == target and j != i:
return True
return False
Complexity
- Hash Set: O(n) time, O(n) space
- Sort+BS: O(n log n) time, O(1) space
Advertisement