1346. Check If N and Its Double Exist
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Intuition
Check if any element in the array equals 2 * another element. Use a HashSet.
Algorithm
- 1Add all elements to a set.
- 2For each element x: if 2*x in set, return true.
Common Pitfalls
- •Edge case: if x=0, need two 0s in the array (2*0=0). Check count of 0s or handle separately.
1346.cs
C#
// Approach: HashSet; for each element check if its double or (if even) its half is already seen.
// Time: O(n) Space: O(n)
public class Solution
{
public bool CheckIfExist(int[] arr)
{
HashSet<int> seen = new HashSet<int>();
foreach (int a in arr)
{
if (seen.Contains(a * 2) || (a % 2 == 0 && seen.Contains(a / 2)))
return true;
seen.Add(a);
}
return false;
}
}Advertisement
Was this solution helpful?