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.
1#include <unordered_set>
2#include <vector>
3using namespace std;
4
5bool checkIfExist(vector<int>& arr) {
6 unordered_set<int> seen;
7 for (int num : arr) {
8 if (seen.count(2 * num) || (num % 2 == 0 && seen.count(num / 2))) {
9 return true;
10 }
11 seen.insert(num);
12 }
13 return false;
14}
This C++ solution utilizes an unordered_set to track numbers that have been iterated over. It checks if the double or half (if even) of each number is present in the set.
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
This Java solution sorts the array and uses nested loops to find any valid indices where one element is the double of another, leveraging the ordered nature of the sorted array.