Check If N and Its Double Exist
Given an array arr of integers, check if there exist two indices i and j such that arri == 2 * arrj and i does not equal j. Return true if such indices exist, otherwise return false. Use a hash set of values seen so far — for each new number, check whether double it or half it (when evenly divisible) has already been seen.
Constraints
- 2 ≤ arr.length ≤ 2000
- -103 ≤ arri ≤ 103
- i != j when comparing arri and arrj
Example
arr = [10, 2, 5, 3]trueExplanation For i = 0 and j = 2, arr0 = 10 = 2 * arr2 = 2 * 5.
In plain terms
- Hash set
- A collection that stores values with no duplicates and lets you check "is this value already in here?" quickly.
Check for double or half among values seen so far
value=10. seen is empty — no match. Add 10 to seen.
What happens in this step
value = arr[0] = 10, seen = {}
2*10=20 not in seen; 10 is even but 5 not in seen
Add 10 to seen.Steps to visualize
- Walk the array, keeping a set of values seen so far.
- For each value, check if 2 * value is already in the set.
- Also check if value is even and value / 2 is already in the set.
- If either check succeeds, return true immediately.
- Otherwise add value to the set and continue; return false if the array ends with no match.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
value=10. seen is empty — no match. Add 10 to seen.
What happens in this step
value = arr[0] = 10, seen = {}
2*10=20 not in seen; 10 is even but 5 not in seen
Add 10 to seen.Solution
function checkIfExist(arr) {
const seen = new Set();
for (const value of arr) {
if (seen.has(2 * value) || (value % 2 === 0 && seen.has(value / 2))) {
return true;
}
seen.add(value);
}
return false;
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
arr = [10, 2, 5, 3] | true | example from the docstring |
arr = [3, 1, 7, 11] | false | no pair satisfies the doubling relationship |
arr = [0, 0] | true | two zeros satisfy 0 == 2 * 0 with distinct indices |
arr = [1, 3] | false | smallest valid input where no value is double another |
arr = [-2, 0, 10, -19, 4, 6, -8] | false | negative values with no matching double |
arr = [-10, 12, -20, -8, 15] | true | negative values where doubling still finds a match |