File: number-of-arithmetic-triplets/solution.py

Date: 2026-06-06

Time: 18:14

Purpose

This file solves LeetCode 2367 — Number of Arithmetic Triplets. Given a strictly increasing array nums and an integer diff, it counts how many triplets (i, j, k) satisfy i < j < k where nums[j] - nums[i] == diff and nums[k] - nums[j] == diff.

Key Components

countarithmetictriplets(nums, diff) -> int

The sole exported function. It uses a single-pass, set-based lookup approach rather than the naive O(n³) triple-nested loop.

Contract:

Patterns

Set-based membership testing. Instead of checking all (i, j, k) combinations, the function builds a seen set as it iterates. For each element x, it checks whether both x - diff and x - 2*diff already exist in seen. If so, (x - 2*diff, x - diff, x) forms a valid triplet.

This is a standard technique for reducing lookup complexity — converting an O(n) scan per element into O(1) hash lookups.

Single-pass accumulation. The loop processes each element exactly once, adding it to seen *after* checking for triplet membership. This ordering is correct because nums is strictly increasing — by the time we reach x, any valid x - diff and x - 2*diff must appear earlier and already be in the set.

Dependencies

Imports: None — pure standard library (uses built-in set).

Imported by: number-of-arithmetic-triplets/test_solution.py directly. The massive "Imported By" list in the prompt is misleading — those are unrelated test files that likely share a common test harness, not actual consumers of this function.

Flow

1. Initialize empty seen set and count = 0.

2. For each x in nums (left to right):

3. Return count.

Invariants

Complexity

This is optimal compared to the brute-force O(n³) and the two-pointer O(n²) alternatives.

Error Handling

None. The function trusts its inputs match the LeetCode contract (valid list, positive diff). No bounds checking, type validation, or exception handling — appropriate for a competitive programming solution.

Topics to Explore

Beliefs