File: find-the-distance-value-between-two-arrays/solution.py

Date: 2026-06-06

Time: 16:45

Purpose

This file solves LeetCode 1385: Find the Distance Value Between Two Arrays. It counts how many elements in arr1 have no element in arr2 within absolute distance d. It's one of ~400+ solution files in the leetcode-implementations repo, each following the same structure: a Solution class with a single method matching the LeetCode signature.

Key Components

Solution.findTheDistanceValue

Contract: Given two integer arrays and a distance threshold d, return the count of elements arr1[i] such that |arr1[i] - arr2[j]| > d for all j.

Signature: (arr1: List[int], arr2: List[int], d: int) -> int

Side effect: Mutates arr2 in-place via .sort(). This is typical for LeetCode solutions but worth noting — the caller's copy of arr2 is reordered.

Patterns

Sort + binary search instead of brute-force nested loop. The naive O(n*m) approach checks every pair. This solution sorts arr2 (O(m log m)) then uses bisect_left to find the insertion point for each arr1 element, reducing the inner check to O(log m). Total: O(m log m + n log m).

The binary search narrows the "is anything within distance d?" question to checking exactly two candidates: the element at the insertion point (the smallest value >= val) and the one just before it (the largest value < val). These are the only two elements that could be closest to val in a sorted array.

Dependencies

Imports:

Imported by: find-the-distance-value-between-two-arrays/test_solution.py (the "Imported By" list in the prompt is a red herring — those are all test files that import their *own* solution.py, not this one)

Flow

1. Sort arr2 in ascending order.

2. For each val in arr1:

3. Return count.

Invariants

Error Handling

None — the function assumes valid inputs per the LeetCode contract (non-empty arrays, integer values). No validation, no exceptions. If arr2 is empty, bisect_left returns 0, both boundary checks fail, and every element counts — which is correct.

Topics to Explore

Beliefs