Skip to content

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:

Input
nums=(10, 20, 30), k=10
Output
True
Input
nums=(5, 15, 25), k=10
Output
True
Input
nums=(1, 2, 3), k=4
Output
True
Input
nums=(2, 4, 6), k=5
Output
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

def is_sum_of_ends_divisible_by_k(nums: tuple, k: int) -> bool:
    return (nums[0] + nums[-1]) % k == 0
def is_sum_of_ends_divisible_by_k(nums: tuple, k: int) -> bool:
    first = nums[0]
    last  = nums[-1]
    total = first + last
    return total % k == 0
def is_sum_of_ends_divisible_by_k(nums: tuple, k: int) -> bool:
    ends = (nums[0], nums[-1])
    return sum(ends) % k == 0

Packs the two ends into a small tuple, then uses sum(). Slightly more verbose but makes the "sum of ends" intent very explicit.

is_sum_of_ends_divisible_by_k = lambda nums, k: (nums[0] + nums[-1]) % k == 0

Key takeaways

01

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].

02

% 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.

03

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.