Given a list of integers nums
and an integer k
, return the difference between the sum of elements in the list that are divisible by k
and the sum of elements that are not divisible by k
.
0
since the sums of both divisible and non-divisible elements would be 0
.k
guaranteed to be non-zero?
k
is always non-zero to avoid division by zero.sum_divisible
and sum_non_divisible
.nums
.k
, add it to sum_divisible
.sum_non_divisible
.sum_divisible
and sum_non_divisible
.def difference_of_sums(nums, k):
sum_divisible = 0
sum_non_divisible = 0
for num in nums:
if num % k == 0:
sum_divisible += num
else:
sum_non_divisible += num
return sum_divisible - sum_non_divisible
# Example usage
nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
print(difference_of_sums(nums, k)) # Output: -9 (0 because (3+6)-(sum(1, 2, 4, 5, 7)) equals -17)
The time complexity of this solution is (O(n)), where (n) is the length of the list nums
. This is because we iterate through the list exactly once, performing a constant amount of work for each element.
The space complexity is (O(1)) since we use only a fixed amount of additional space regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?