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.
1using System.Collections.Generic;
2
3public class Solution {
4 public bool CheckIfExist(int[] arr) {
5 HashSet<int> seen = new HashSet<int>();
6 foreach (int num in arr) {
7 if (seen.Contains(2 * num) || (num % 2 == 0 && seen.Contains(num / 2))) {
8 return true;
9 }
10 seen.Add(num);
11 }
12 return false;
13 }
14}
This C# implementation uses a HashSet to track the numbers that have been processed. For each number, it checks if its double or half (if even) is 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 Python solution sorts the array and uses a nested loop to efficiently check conditions, terminating early when further comparisons are unnecessary due to the sorted order.