Check If N and Its Double Exist - Problem
Check If N and Its Double Exist
You're given an array of integers, and you need to find if there exists a magical pair! Specifically, you need to determine if there are two different positions in the array where one element is exactly twice the value of another.
The Challenge:
Find two indices
•
•
•
Goal: Return
Example: In
You're given an array of integers, and you need to find if there exists a magical pair! Specifically, you need to determine if there are two different positions in the array where one element is exactly twice the value of another.
The Challenge:
Find two indices
i and j such that:•
i ≠ j (different positions)•
0 ≤ i, j < arr.length (valid indices)•
arr[i] == 2 * arr[j] (one is double the other)Goal: Return
true if such a pair exists, false otherwise.Example: In
[10, 2, 5, 3], we have 10 = 2 × 5, so return true! Input & Output
example_1.py — Basic positive case
$
Input:
[10, 2, 5, 3]
›
Output:
true
💡 Note:
We can find two indices i=0 and j=2 where arr[0] = 10 and arr[2] = 5, and 10 = 2 × 5. The double relationship exists between elements at different positions.
example_2.py — No valid pairs
$
Input:
[3, 1, 7, 11]
›
Output:
false
💡 Note:
No element in the array is exactly double of any other element. We need to check: 3×2=6 (not in array), 1×2=2 (not in array), 7×2=14 (not in array), 11×2=22 (not in array).
example_3.py — Zero edge case
$
Input:
[-2, 0, 10, -19, 4, 6, -8]
›
Output:
false
💡 Note:
Even though we have both positive and negative numbers including zero, no element is exactly double of another. Note that 0 would need another 0 to form a valid pair (0 = 2 × 0), but there's only one zero.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize the Registry
Start with an empty registration system (hash set) to track dancer heights
2
Process Each Dancer
As each dancer arrives, immediately check if their ideal partner is already registered
3
Check for Perfect Match
Look for someone exactly half their height OR double their height in the registry
4
Register or Match
If no match found, add them to registry. If match found, celebrate the perfect pair!
Key Takeaway
🎯 Key Insight: Transform the pair-finding problem into instant lookups by building a registry as we go, achieving optimal O(n) performance!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with O(1) hash table operations
✓ Linear Growth
Space Complexity
O(n)
Hash set can store up to n elements in worst case
⚡ Linearithmic Space
Constraints
- 2 ≤ arr.length ≤ 500
- -103 ≤ arr[i] ≤ 103
- Array contains at least 2 elements
- Elements can be negative, zero, or positive
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code