~/problems / Arrays & hashing / Prefix sums and difference arrays

Continuous Subarray Sum

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A farm logs how many eggs its hens lay each day: eggs[i] on day i. Egg boxes hold exactly k eggs. The farmer wants to know whether some stretch of at least two consecutive days laid a total that fills whole boxes with no egg left over, that is, a total that is a multiple of k. A total of 0 counts too (zero full boxes).

Write check_subarray_sum(eggs: list[int], k: int) -> bool.

check_subarray_sum([5, 3, 8, 2], 6)    # True: all four days give 18, three boxes
check_subarray_sum([5, 3, 8, 2], 7)    # False: the totals 8, 11, 10, 16, 13, 18 miss every multiple of 7
check_subarray_sum([12], 6)            # False: 12 fills two boxes, but it's only one day
check_subarray_sum([3, 0, 0], 7)       # True: days 1 and 2 lay 0 eggs in total

Constraints: 1 <= len(eggs) <= 2 * 10^5, 0 <= eggs[i] <= 10^9, 1 <= k <= 2^31 - 1. In C++ and Java, running totals overflow 32 bits.

⭐ Bonus: trying every stretch still passes; a speed test with 200,000 days earns a star in O(n).

Show hint

two running totals with the same remainder mod k differ by a multiple of k. Remember where each remainder first appeared, and check the stretch between is at least two days long.

Topic: Prefix sums and difference arrays. O(1) range sums (1D and 2D); O(1) range updates with difference arrays.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc