Given an array arr of integers, check if there exists two integers N and M such that N is twice M (i.e., N = 2 * M).
In other words, determine if there are two distinct indices i and j in the array such that arr[i] is double arr[j].
You need to return True if such elements exist, otherwise return False.
0 = 2 * 0.True or False).x in the array, we check if x/2 or 2*x exists in the set.x/2 or 2*x is found in the set, we return True.False at the end.def checkIfExist(arr):
seen = set()
for x in arr:
if x / 2 in seen or x * 2 in seen:
return True
seen.add(x)
return False
O(n)) and each check and insertion in the set takes O(1) on average. Hence, the total time complexity is O(n) where n is the length of the array.seen to track the elements we’ve come across.x in the array:
x / 2 or 2 * x is already in seen.True.x to the set.True, it means no such pair exists, and we return False.arr = [10, 2, 5, 3], the function should return True because 10 is twice 5.arr = [7, 1, 14, 11], the function should return True because 14 is twice 7.arr = [3, 1, 7, 11], the function should return False because no element is twice another in the array.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?