1346. Check If N and Its Double Exist #899
-
Topics: Given an array
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a hash table (associative array) to track the elements we have already encountered while iterating through the array. The idea is to check for each element Here’s a step-by-step solution: Plan:
Let's implement this solution in PHP: 1346. Check If N and Its Double Exist <?php
function checkIfExist($arr) {
$hashTable = array();
foreach ($arr as $num) {
// Check if double of the number exists in the hash table
if (isset($hashTable[$num * 2])) {
return true;
}
// Check if half of the number exists in the hash table (only if num is even)
if ($num % 2 == 0 && isset($hashTable[$num / 2])) {
return true;
}
// Add the current number to the hash table
$hashTable[$num] = true;
}
return false;
}
// Example usage
$arr1 = [10, 2, 5, 3];
$arr2 = [3, 1, 7, 11];
echo checkIfExist($arr1) ? 'true' : 'false'; // Output: true
echo "\n";
echo checkIfExist($arr2) ? 'true' : 'false'; // Output: false
?> Explanation:
Time Complexity:
Space Complexity:
|
Beta Was this translation helpful? Give feedback.
We can use a hash table (associative array) to track the elements we have already encountered while iterating through the array. The idea is to check for each element
arr[i]
if its double (i.e.,2 * arr[i]
) or half (i.e.,arr[i] / 2
if it's an even number) has already been encountered.Here’s a step-by-step solution:
Plan:
arr[i]
, check if we have seen2 * arr[i]
orarr[i] / 2
(ifarr[i]
is even) in the hash table.true
.arr[i]
to the hash table and continue to the next element.false
.Let's implement this solution in PHP: 1346. Check If N and Its Doub…