Check If N and Its Double Exist
Check If N and Its Double Exist is a easy arrays & hashing problem solved with the hash set lookup pattern.
The best approach, optimal (hash set of seen values), runs in O(n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (check every pair) up.
Problem
You are given an array of integers arr.
Decide whether it contains two different positions i and j (so i != j) such that the value at one position is exactly twice the value at the other:
arr[i] == 2 * arr[j]
Return true if such a pair of indexes exists, and false otherwise.
Examples
Example 1
- Input
arr = [7, 1, 14, 11]- Output
true- Why
- 14 sits at index 2 and 7 at index 0, and 14 = 2 * 7.
Example 2
- Input
arr = [6, 1, 4, 13]- Output
false- Why
- The doubles 12, 2, 8 and 26 are all missing from the array, so no element is twice another.
Example 3
- Input
arr = [-3, 0, 5, -6]- Output
true- Why
- -6 = 2 * (-3). Negative numbers double just like positive ones.
Example 4
- Input
arr = [0, 9, 2]- Output
false- Why
- 0 is its own double, but the indexes must be different, and there is only one 0.
Constraints
2 <= arr.length <= 500-10^3 <= arr[i] <= 10^3
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (4 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (check every pair) | O(n²) | O(1) |
| Sort and binary search | O(n log n) | O(1) |
| Optimal (hash set of seen values) | O(n) | O(n) |
1Brute force (check every pair)
O(n²)n * (n - 1) ordered pairs of indexes, each checked in O(1).O(1)Only the two loop indexes.Try every ordered pair of different indexes i and j and test whether arr[i] equals twice arr[j]. The test i != j makes sure a lone 0 is not matched with itself.
- For every i and every j with i != j: if arr[i] == 2 * arr[j], return true.
- Return false.
class Solution {
public boolean checkIfExist(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && arr[i] == 2 * arr[j]) return true;
}
}
return false;
}
}class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
n = len(arr)
for i in range(n):
for j in range(n):
if i != j and arr[i] == 2 * arr[j]:
return True
return Falseclass Solution {
public:
bool checkIfExist(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && arr[i] == 2 * arr[j]) return true;
}
}
return false;
}
};function checkIfExist(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i !== j && arr[i] === 2 * arr[j]) return true;
}
}
return false;
}2Sort and binary search
O(n log n)Sorting costs O(n log n), then n binary searches cost O(log n) each.O(1)The search uses a few variables; the sort works in place (apart from the sort's own stack).Sort the array. For each element x at index i, binary search for the first position lo holding a value of at least 2 * x. If arr[lo] is 2 * x at an index other than i, we have a pair. The only way lo can be i itself is x = 0 (then 2 * x = x); in that case a second 0 right after it still gives a pair.
- Sort arr.
- For each index i, let target = 2 * arr[i] and find lo, the first index with arr[lo] >= target.
- If lo < n and arr[lo] == target, return true when lo != i, or when lo + 1 < n and arr[lo + 1] == target.
- Return false.
class Solution {
public boolean checkIfExist(int[] arr) {
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n; i++) {
int target = 2 * arr[i];
int lo = 0, hi = n;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (arr[mid] < target) lo = mid + 1;
else hi = mid;
}
if (lo < n && arr[lo] == target) {
if (lo != i || (lo + 1 < n && arr[lo + 1] == target)) return true;
}
}
return false;
}
}class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
arr.sort()
n = len(arr)
for i in range(n):
target = 2 * arr[i]
lo, hi = 0, n
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
if lo < n and arr[lo] == target:
if lo != i or (lo + 1 < n and arr[lo + 1] == target):
return True
return Falseclass Solution {
public:
bool checkIfExist(vector<int>& arr) {
sort(arr.begin(), arr.end());
int n = arr.size();
for (int i = 0; i < n; i++) {
int target = 2 * arr[i];
int lo = 0, hi = n;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (arr[mid] < target) lo = mid + 1;
else hi = mid;
}
if (lo < n && arr[lo] == target) {
if (lo != i || (lo + 1 < n && arr[lo + 1] == target)) return true;
}
}
return false;
}
};function checkIfExist(arr) {
arr.sort((a, b) => a - b);
const n = arr.length;
for (let i = 0; i < n; i++) {
const target = 2 * arr[i];
let lo = 0, hi = n;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] < target) lo = mid + 1;
else hi = mid;
}
if (lo < n && arr[lo] === target) {
if (lo !== i || (lo + 1 < n && arr[lo + 1] === target)) return true;
}
}
return false;
}3Optimal (hash set of seen values)
O(n)One pass with O(1) average set operations per element.O(n)The set can hold all n values.Scan the array once and keep a set of the values seen so far. A pair can be found at the moment its later element arrives: the new value x is either the double of an earlier value (x is even and x / 2 is in the set) or the half of an earlier value (2 * x is in the set). Because only earlier elements are in the set, x is never matched with itself, and a second 0 finds the first one.
- Create an empty set seen.
- For each x in arr: if seen contains 2 * x, or x is even and seen contains x / 2, return true.
- Add x to seen.
- Return false.
class Solution {
public boolean checkIfExist(int[] arr) {
Set<Integer> seen = new HashSet<>();
for (int x : arr) {
if (seen.contains(2 * x) || (x % 2 == 0 && seen.contains(x / 2))) return true;
seen.add(x);
}
return false;
}
}class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
seen = set()
for x in arr:
if 2 * x in seen or (x % 2 == 0 and x // 2 in seen):
return True
seen.add(x)
return Falseclass Solution {
public:
bool checkIfExist(vector<int>& arr) {
unordered_set<int> seen;
for (int x : arr) {
if (seen.count(2 * x) || (x % 2 == 0 && seen.count(x / 2))) return true;
seen.insert(x);
}
return false;
}
};function checkIfExist(arr) {
const seen = new Set();
for (const x of arr) {
if (seen.has(2 * x) || (x % 2 === 0 && seen.has(x / 2))) return true;
seen.add(x);
}
return false;
}Edge cases to test
- A single 0: it equals its own double, but i and j must differ, so it does not count
- Two or more zeros: 0 = 2 * 0 at two different indexes, so the answer is true
- Negative values: -8 is the double of -4
- An odd number is never a double, so only even numbers can be the arr[i] side
- The double can appear before or after its half in the array
- Duplicates of a nonzero value (5, 5) do not help: 5 is not 2 * 5
Hints
Hint 1
Checking every pair of indexes works, since the array has at most 500 elements.
Hint 2
For each number x you only need to know whether 2 * x is somewhere else in the array. A hash set answers that in O(1).
Hint 3
Scan left to right with a set of the numbers seen so far. For x, look up 2 * x and, if x is even, x / 2. This also handles the zero case without any special rule.
FAQ
What is the best time complexity for Check If N and Its Double Exist?
Optimal (hash set of seen values) runs in O(n) time and O(n) extra space. One pass with O(1) average set operations per element.
Which pattern does Check If N and Its Double Exist use?
It is a arrays & hashing problem that uses the hash set lookup pattern. Other problems with the same pattern: Longest Consecutive Sequence, Contains Duplicate, Fair Candy Swap.
Is there a brute force solution for Check If N and Its Double Exist?
Yes. Brute force (check every pair) takes O(n²) time and O(1) space. Try every ordered pair of different indexes i and j and test whether arr[i] equals twice arr[j].
Which edge cases should I test for Check If N and Its Double Exist?
A single 0: it equals its own double, but i and j must differ, so it does not count; Two or more zeros: 0 = 2 0 at two different indexes, so the answer is true; Negative values: -8 is the double of -4; An odd number is never a double, so only even numbers can be the arr[i] side; The double can appear before or after its half in the array; Duplicates of a nonzero value (5, 5) do not help: 5 is not 2 5.