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]
Return true
if such elements exist, otherwise return false
.
false
.1 <= arr.length <= 500
.x
:
x * 2
or x / 2
(only if x
is even) exists in the set.true
.x
to the set.false
.This approach ensures we check every possible pair in linear time, making it efficient.
import java.util.HashSet;
public class Solution {
public boolean checkIfExist(int[] arr) {
HashSet<Integer> seen = new HashSet<>();
for (int num : arr) {
if (seen.contains(num * 2) || (num % 2 == 0 && seen.contains(num / 2))) {
return true;
}
seen.add(num);
}
return false;
}
}
This solution is efficient both in terms of time and space, making it suitable for the given constraints.
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?