File: difference-between-element-sum-and-digit-sum-of-an-array/solution.py

Date: 2026-06-06

Time: 16:23

difference-between-element-sum-and-digit-sum-of-an-array/solution.py

Purpose

This file solves LeetCode 2535. It computes two sums over an input array — the element sum (sum of the numbers themselves) and the digit sum (sum of every individual digit across all numbers) — then returns their absolute difference.

It follows the repo's convention: one solution file per problem directory, exporting a single function that encapsulates the algorithm.

Key Components

differencebetweenelementanddigit_sum(nums: list[int]) -> int — The sole public function. Contract:

Patterns

Single-pass accumulation. Both sums are computed in one loop over nums, avoiding a second traversal. The digit extraction happens inline via repeated % 10 / //= 10 — standard modular arithmetic rather than string conversion. This is the idiomatic numeric approach and avoids allocating intermediate string objects.

Destructive parameter reuse. The loop variable num is mutated in-place by the while num > 0 loop. This is safe because num is a rebinding of the loop variable, not a mutation of the input list.

Dependencies

Imports: None. The solution is self-contained with no stdlib or third-party dependencies.

Imported by: The test_solution.py in the same directory imports this function. The massive "Imported By" list in the prompt is misleading — those are unrelated test files that happen to share a test runner infrastructure, not actual consumers of this function.

Flow

1. Initialize elementsum and digitsum to 0.

2. For each num in nums:

3. Return abs(elementsum - digitsum).

For input [1, 15, 6, 3]: element sum = 25, digit sum = 1+1+5+6+3 = 16, result = 9.

Invariants

Error Handling

None. The function trusts its caller to provide a valid list[int] of positive integers, consistent with LeetCode's constraint-based model. An empty list returns 0 (both sums start at 0).

Topics to Explore

Beliefs