Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Every integer from one through n belongs to exactly one of two groups according to whether it is divisible by m. Summing those groups separately follows the requested difference directly.
Approach
Initialize the divisible and non-divisible sums to zero. Scan the inclusive range from one to n, using the remainder modulo m to choose which sum receives each value. Return the non-divisible sum minus the divisible sum. The result is allowed to be negative; for example, when m = 1, every value belongs to the subtracted group. This reference implementation enumerates the range rather than using a closed-form series formula.
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
num1, num2 = 0, 0
for x in range(1, n + 1):
if x % m != 0:
num1 += x
else:
num2 += x
return num1 - num2Complexity analysis
Time: O(n). Auxiliary space: O(1).
