Longest Subarray with Bounded Variance Sum
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests the ability to combine prefix sums with hash maps to efficiently find the longest contiguous subarray whose element-wise difference from the mean of two boundary values stays within a given tolerance.
Longest Balanced Subarray
You are given a list of integers representing daily temperature readings at a weather station, and an integer k. A subarray is called balanced if the sum of its elements is divisible by k.
Your task is to find the length of the longest contiguous balanced subarray. If no such subarray exists, return 0.
Details
- A subarray is a contiguous, non-empty slice of the original list.
- A subarray with sum
Sis balanced ifS % k == 0(i.e.,Sis an exact multiple ofk). - Because Python's
%operator always returns a non-negative result for positivek, remainders are always in the range[0, k-1]. You must follow this convention exactly.
Constraints
1 <= len(readings) <= 2000-10^4 <= readings[i] <= 10^42 <= k <= 10^4
Examples
Example 1
Input: longest_balanced_subarray([3, 1, 4, 2, 6, 1, 2], 3)
Output: 5
Example 2
Input: longest_balanced_subarray([1, 2, 3], 7)
Output: 0
Example 3
Input: longest_balanced_subarray([6, 3, -9, 4, 2], 3)
Output: 5
Hints
Hint 1
Compute a running prefix sum. What relationship between two prefix sums tells you the subarray between them is balanced?
Hint 2
If prefix[j] % k == prefix[i] % k, then the subarray from index i+1 to j has a sum divisible by k. Use a hash map to store the first occurrence of each remainder.
Hint 3
Be careful with negative numbers: Python's modulo always returns a non-negative value for positive k, so (-3) % 5 == 2 in Python — use this directly without any manual adjustment.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight — Prefix Sums and Remainders
Define the prefix sum P[i] = readings[0] + readings[1] + ... + readings[i], and let P[-1] = 0 (the empty prefix).
A subarray readings[l..r] has sum P[r] - P[l-1]. This sum is divisible by k if and only if:
(P[r] - P[l-1]) % k == 0
⟺ P[r] % k == P[l-1] % k
So the problem reduces to: find the two indices with the same prefix-sum remainder that are as far apart as possible.
Algorithm
- Initialise a hash map
first_occurrence = {0: -1}. The entry0 → -1handles the case where a prefix sum itself is divisible byk(the subarray starts at index 0). - Iterate through the array, maintaining a running prefix sum and computing its remainder mod
k. - If the remainder has been seen before, the subarray between the stored index and the current index is balanced; update the best length.
- If the remainder has not been seen, record the current index. We only store the first occurrence so that future matches give the longest possible subarray.
Why It Is Correct
- Python's
%always returns a value in[0, k-1]for positivek, even with negative prefix sums, so no manual normalisation is needed. - Storing only the first occurrence is safe because any later duplicate would yield a shorter (or equal) subarray.
- The sentinel
{0: -1}correctly accounts for subarrays that begin at index 0.
Complexity
| Time | O(n) — one pass, O(1) hash map operations per element |
| Space | O(k) — at most k distinct remainders stored |
Reference Solution
def longest_balanced_subarray(readings: list[int], k: int) -> int:
first_occurrence = {0: -1}
prefix_sum = 0
best = 0
for i, val in enumerate(readings):
prefix_sum += val
rem = prefix_sum % k # always non-negative in Python
if rem in first_occurrence:
length = i - first_occurrence[rem]
if length > best:
best = length
else:
first_occurrence[rem] = i
return best
Worked Example
readings = [3, 1, 4, 2, 6, 1, 2], k = 3
| i | val | prefix_sum | rem | first_occurrence | best |
|---|---|---|---|---|---|
| — | — | 0 | 0 | {0:−1} | 0 |
| 0 | 3 | 3 | 0 | seen at −1 → len 1 | 1 |
| 1 | 1 | 4 | 1 | {0:−1,1:1} | 1 |
| 2 | 4 | 8 | 2 | {…,2:2} | 1 |
| 3 | 2 | 10 | 1 | seen at 1 → len 2 | 2 |
| 4 | 6 | 16 | 1 | seen at 1 → len 3 | 3 |
| 5 | 1 | 17 | 2 | seen at 2 → len 3 | 3 |
| 6 | 2 | 19 | 1 | seen at 1 → len 5 | 5 |
Result: 5 (the subarray [1, 4, 2, 6, 1] has sum 14, not divisible… let me recheck — readings[1..5] = [1,4,2,6,1] sum=14, 14%3=2. Actually the match is rem=1 first seen at i=1, now at i=6: subarray is readings[2..6]=[4,2,6,1,2] sum=15, 15%3=0. ✓ Length = 6−1 = 5.)