File: check-if-n-and-its-double-exist/solution.py

Date: 2026-06-06

Time: 15:40

check-if-n-and-its-double-exist/solution.py

Purpose

This file implements LeetCode problem 1346: "Check If N and Its Double Exist." It owns both the solution logic and its test suite in a single module. The problem asks whether any two distinct indices i and j exist in an array such that arr[i] == 2 * arr[j].

Key Components

checkIfExist(arr: list[int]) -> bool — The core solver. Performs a single-pass scan using a hash set to check, for each element x, whether its double (2x) or its half (x/2) has already been seen. Returns True on the first match, False if the array is exhausted.

TestCheckIfExist — Eight unit tests covering the standard cases: positive match, no match, zero-handling (both duplicate zeros and a single zero), negative numbers, minimum-length arrays, and a double appearing later in the array.

Patterns

Single-pass hash set lookup. Rather than using a brute-force O(n^2) nested loop, the solution builds a seen set incrementally. For each element x, it checks two conditions before inserting x:

1. 2 * x in seen — has a value that is double of x already appeared?

2. x % 2 == 0 and x // 2 in seen — is x even, and has its half already appeared?

The order matters: checking before inserting ensures i != j naturally (an element can't match itself), except when the same value appears twice — which is correct behavior (e.g., [0, 0]).

Self-contained module. Solution and tests coexist in one file with if _name == "main_": unittest.main(), following the repo-wide convention.

Dependencies

Imports: Only unittest from the standard library. No external dependencies.

Imported by: The test_solution.py in this same directory, plus hundreds of other test files across the repo. The "Imported By" list in the prompt is misleading — those other test files don't actually import *this* solution. That list likely reflects a shared test runner or a cross-referencing artifact from the code-expert tooling, not real Python import edges.

Flow

1. Initialize empty seen: set.

2. For each x in arr:

3. If loop completes → return False.

This is O(n) time and O(n) space.

Invariants

Error Handling

None. The function assumes valid input per the LeetCode contract (a list of integers with length >= 2). No bounds checking, no exception handling.

Topics to Explore

Beliefs