Problem Description
Given an array of integers, determine whether there exist two distinct indices i and j such that arr[i] is double arr[j].
Key Insights
- Use a hash set to track numbers seen so far.
- For every number x in the array, check if 2*x is in the set.
- Additionally, if x is even, check if x/2 is in the set.
- This one-pass method handles zero and negative numbers without special cases.
- Alternatively, sorting combined with two pointers is possible but less efficient.
Space and Time Complexity
Time Complexity: O(n) since we iterate through the array once. Space Complexity: O(n) due to the hash set used for storing seen numbers.
Solution
We iterate through the array while storing each number in a hash set. For each number, we check if either its double or, if it is even, its half already exists in the set. This ensures that we efficiently detect any pair satisfying arr[i] == 2 * arr[j]. The solution handles edge cases such as the number 0 (since 0 == 2 * 0) and negative numbers seamlessly.