Check If N and Its Double Exist
LeetCode 1468 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given an array arr of integers, check if there exist two indices i and j such that :
- `i != j`
- `0 <= i, j < arr.length`
- `arr[i] == 2 * arr[j]`
Example 1:
Input: arr = [10,2,5,3]
Output: true
Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]
Example 2:
Input: arr = [3,1,7,11]
Output: false
Explanation: There is no i and j that satisfy the conditions.
Constraints:
- `2 <= arr.length <= 500`
- `-10^3 <= arr[i] <= 10^3`
Topics: Array, Hash Table, Two Pointers, Binary Search, Sorting
Approachβ
Two Pointersβ
Use two pointers to traverse the array, reducing the search space at each step. This avoids the need for nested loops, bringing complexity from O(nΒ²) to O(n) or O(n log n) if sorting is involved.
Array is sorted or can be sorted, and you need to find pairs/triplets that satisfy a condition.
Binary Searchβ
Binary search reduces the search space by half at each step. The key insight is identifying the monotonic property β what condition lets you decide to go left or right?
Sorted array, or searching for a value in a monotonic function/space.
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
Solutionsβ
Solution 1: C# (Best: 100 ms)β
| Metric | Value |
|---|---|
| Runtime | 100 ms |
| Memory | 25.1 MB |
| Date | 2020-02-11 |
public class Solution {
public bool CheckIfExist(int[] arr) {
List<int> vals = new List<int>();
vals.Add(arr[0]);
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] % 2 == 0)
{
if (vals.Contains(arr[i] / 2) || vals.Contains(arr[i] * 2))
{
return true;
}
}
else
{
if (vals.Contains(arr[i] * 2))
{
return true;
}
}
vals.Add(arr[i]);
}
return false;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Two Pointers | $O(n)$ | $O(1)$ |
| Binary Search | $O(log n)$ | $O(1)$ |
| Sort + Process | $O(n log n)$ | $O(1) to O(n)$ |
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Ask: "Can I sort the array?" β Sorting often enables two-pointer techniques.
- Hash map gives O(1) lookup β think about what to use as key vs value.
- Precisely define what the left and right boundaries represent, and the loop invariant.
- LeetCode provides 3 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: Loop from i = 0 to arr.length, maintaining in a hashTable the array elements from [0, i - 1].
Hint 2: On each step of the loop check if we have seen the element 2 * arr[i] so far.
Hint 3: Also check if we have seen arr[i] / 2 in case arr[i] % 2 == 0.