Check If N and Its Double Exist
Given an array of integers, check if there exist two indices i and j such that i != j and either arr[i] = 2 * arr[j] or arr[j] = 2 * arr[i]. In other words, check if any element is exactly double another element.
A brute force double loop checks every pair in O(n²). Sorting the array and using binary search reduces this to O(n log n). For each element, search for its double using binary search. Because the array is sorted, binary search finds the target in O(log n) time.
An even simpler approach uses a hash set for O(n) time: iterate through the array, for each element check if its double or half (if even) exists in the set. If so, return true. Otherwise, add the element to the set and continue.
Edge cases include zeros (0*2=0, needs two zeros at different indices), negative numbers (-3*2=-6), and multiple duplicates. The hash set approach naturally handles these by checking for the double and half before inserting the current element.
The hash set approach is O(n) and works well for this problem. The key insight is checking both 2*n and n/2 (when n is even) against the set of previously seen elements. This ensures we find a pair regardless of which element appears first in the array.
Example Input & Output
No element is double another.
Two zeros: 0*2=0.
-2*2=-4 at indices 0 and 3.
2*7=14 at indices 0 and 2.
2*5=10, indices 0 and 2.
Algorithm Flow

Solution Approach
Hash set approach: for each n, check if 2*n or n/2 is already seen. If found, return true. Add n to the set.
Time O(n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public boolean solution(int[] arr) {
Set<Integer> seen = new HashSet<>();
for (int n : arr) {
if (seen.contains(n * 2) || (n % 2 == 0 && seen.contains(n / 2))) return true;
seen.add(n);
}
return false;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
