Leetcode #2894: Divisible and Non-divisible Sums Difference
In this guide, we solve Leetcode #2894 Divisible and Non-divisible Sums Difference in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given positive integers n and m. Define two integers as follows: num1: The sum of all integers in the range [1, n] (both inclusive) that are not divisible by m.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Math
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: n = 10, m = 3
Output: 19
Explanation: In the given example:
- Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37.
- Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18.
We return 37 - 18 = 19 as the answer.
Python Solution
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
return sum(i if i % m else -i for i in range(1, n + 1))
Complexity
The time complexity is , where is the given integer. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.