Leetcode 1346. Check If N and Its Double Exist
Given an array arr
of integers, check if there exist two indices i
and j
such that:
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
or arr[j] == 2 * arr[i]
To solve this problem efficiently, we can use a hash set. Here’s the step-by-step strategy:
x
, check if 2 * x
or x / 2
(only if x
is even) exists in the set.true
.false
.#include <unordered_set>
#include <vector>
using namespace std;
bool checkIfExist(vector<int>& arr) {
unordered_set<int> seen;
for (int num : arr) {
if (seen.count(2 * num) > 0 || (num % 2 == 0 && seen.count(num / 2) > 0)) {
return true;
}
seen.insert(num);
}
return false;
}
seen
to keep track of the elements we have encountered so far.2 * num
(double of the current number) already exists in the hash set.num / 2
(half of the current number) exists in the hash set.true
. If no conditions are met by the end of the loop, return false
.O(n)
where n
is the number of elements in the array. We are doing a constant-time lookup and insertion for each element in the array.O(n)
because we store each element in the hash set.This approach ensures that we efficiently check the conditions in linear time with respect to the size of the input array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?