easy

Check If N and Its Double Exist

Check whether one array value is exactly double another.

1. Define the problem

Check If N and Its Double Exist

Given an array arr of integers, check if there exist two indices i and j such that arri == 2 * arrj and i does not equal j. Return true if such indices exist, otherwise return false. Use a hash set of values seen so far — for each new number, check whether double it or half it (when evenly divisible) has already been seen.

Constraints

  • 2 ≤ arr.length ≤ 2000
  • -103 ≤ arri ≤ 103
  • i != j when comparing arri and arrj

Example

Inputarr = [10, 2, 5, 3]
Outputtrue

Explanation For i = 0 and j = 2, arr0 = 10 = 2 * arr2 = 2 * 5.

2. Know the words first

In plain terms

Hash set
A collection that stores values with no duplicates and lets you check "is this value already in here?" quickly.
3. Visualize the solution

Check for double or half among values seen so far

Check for double or half among values seen so far
Statusinit

value=10. seen is empty — no match. Add 10 to seen.

What happens in this step

value = arr[0] = 10, seen = {}
2*10=20 not in seen; 10 is even but 5 not in seen

Add 10 to seen.
Step 1 of 4

Steps to visualize

  1. Walk the array, keeping a set of values seen so far.
  2. For each value, check if 2 * value is already in the set.
  3. Also check if value is even and value / 2 is already in the set.
  4. If either check succeeds, return true immediately.
  5. Otherwise add value to the set and continue; return false if the array ends with no match.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Check for double or half among values seen so far
Statusinit

value=10. seen is empty — no match. Add 10 to seen.

What happens in this step

value = arr[0] = 10, seen = {}
2*10=20 not in seen; 10 is even but 5 not in seen

Add 10 to seen.
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function checkIfExist(arr) {
  const seen = new Set();

  for (const value of arr) {
    if (seen.has(2 * value) || (value % 2 === 0 && seen.has(value / 2))) {
      return true;
    }

    seen.add(value);
  }

  return false;
}
Time
O(n)
Space
O(n)
6. Test cases

Test cases

InputExpectedCovers
arr = [10, 2, 5, 3]trueexample from the docstring
arr = [3, 1, 7, 11]falseno pair satisfies the doubling relationship
arr = [0, 0]truetwo zeros satisfy 0 == 2 * 0 with distinct indices
arr = [1, 3]falsesmallest valid input where no value is double another
arr = [-2, 0, 10, -19, 4, 6, -8]falsenegative values with no matching double
arr = [-10, 12, -20, -8, 15]truenegative values where doubling still finds a match