#1346
Check If N and Its Double Exist
EasyArrayHash TableTwo PointersBinary SearchSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a hash set allows us to store elements we have seen so far, enabling O(1) average time complexity for lookups. This significantly reduces the number of comparisons needed.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty hash set.
- 2Step 2: Loop through each element in the array.
- 3Step 3: For each element, check if double the value exists in the hash set. If it does, return true.
- 4Step 4: Add the current element to the hash set.
- 5Step 5: If no pairs are found after the loop, return false.
solution.py10 lines
1# Full working Python code
2arr = [10, 2, 5, 3]
3def checkIfExist(arr):
4 seen = set()
5 for num in arr:
6 if 2 * num in seen or (num % 2 == 0 and num // 2 in seen):
7 return True
8 seen.add(num)
9 return False
10print(checkIfExist(arr))ℹ
Complexity note: This complexity is linear because we traverse the array once, and the hash set operations (add and check) are average O(1).
- 1Using a hash set can significantly reduce the time complexity of the solution.
- 2Checking both conditions (double and half) ensures we cover all cases.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.