S1Q2 · Sum of Ends Divisible by K¶
⚡ Quick Reference
Function: is_sum_of_ends_divisible_by_k(nums: tuple, k: int) -> bool
Core idea: add first and last elements, check if divisible by k.
def is_sum_of_ends_divisible_by_k(nums: tuple, k: int) -> bool:
return (nums[0] + nums[-1]) % k == 0
Key rules:
- First element: nums[0], last element: nums[-1]
- Divisible → (first + last) % k == 0
- k is guaranteed non-zero - no division-by-zero guard needed
Problem Statement¶
Problem
Write a function is_sum_of_ends_divisible_by_k(nums, k) that returns True if the sum of the first and last elements of the tuple is divisible by k.
Examples:
nums=(10, 20, 30), k=10
True
nums=(5, 15, 25), k=10
True
nums=(1, 2, 3), k=4
True
nums=(2, 4, 6), k=5
False
Tracing all examples¶
nums |
nums[0] |
nums[-1] |
sum | sum % k |
Result |
|---|---|---|---|---|---|
(10, 20, 30), k=10 |
10 | 30 | 40 | 40 % 10 = 0 ✅ | True |
(5, 15, 25), k=10 |
5 | 25 | 30 | 30 % 10 = 0 ✅ | True |
(1, 2, 3), k=4 |
1 | 3 | 4 | 4 % 4 = 0 ✅ | True |
(2, 4, 6), k=5 |
2 | 6 | 8 | 8 % 5 = 3 ❌ | False |
Middle elements are irrelevant
Only nums[0] and nums[-1] matter. Any elements in between are completely ignored. This is why the problem guarantees at least two elements - a one-element tuple would have the same element at both ends.
Solution approaches¶
Key takeaways¶
nums[-1] for the last element
Negative indexing counts from the end. nums[-1] is always the last element regardless of the tuple's length - no need to compute nums[len(nums)-1].
% k == 0 for divisibility
The modulo operator gives the remainder. If the remainder is 0, the number is exactly divisible. This is the standard Python divisibility check.
Ignore the middle
The problem only asks about the first and last elements. Don't be tempted to sum the entire tuple - only nums[0] and nums[-1] are needed.