Sponsored
Sponsored
This approach uses a Hash Set to store elements as we iterate through the array. For each element, we check if its double or half (only if it's even) exists in the set. This allows for efficient lookup and insertion operations.
Time Complexity: O(n), because we iterate through the array once and do constant time operations for each element.
Space Complexity: O(1), since the hash set size is fixed regardless of input size.
1import java.util.HashSet;
2
3public class Solution {
4 public boolean checkIfExist(int[] arr) {
5 HashSet<Integer> set = new HashSet<>();
6 for (int num : arr) {
7 if (set.contains(2 * num) || (num % 2 == 0 && set.contains(num / 2))) {
8 return true;
9 }
10 set.add(num);
11 }
12 return false;
13 }
14}
This Java solution uses a HashSet to store numbers as they are visited. For each number, it checks for the presence of twice the number or half if the number is even.
This approach involves sorting the array first. Once sorted, we can use two pointers to find if there exist indices i and j such that one element is twice the other. Sorting helps to systematically check this condition.
Time Complexity: O(n log n) for sorting, then O(n^2) for the two-pointer search.
Space Complexity: O(1) as it sorts in place.
1#include <algorithm>
using namespace std;
bool checkIfExist(vector<int>& arr) {
sort(arr.begin(), arr.end());
for (int i = 0; i < arr.size(); i++) {
for (int j = i + 1; j < arr.size() && arr[j] <= 2 * arr[i]; j++) {
if (arr[j] == 2 * arr[i] || arr[i] == 2 * arr[j]) {
return true;
}
}
}
return false;
}
This C++ implementation sorts the array and uses the two-pointer technique to check pairs of elements, taking advantage of the sorted order to efficiently check conditions.