KatInterview

Longest Subarray with Bounded Variance Sum

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarraysprefix sumshash maps

Last 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 S is balanced if S % k == 0 (i.e., S is an exact multiple of k).
  • Because Python's % operator always returns a non-negative result for positive k, 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^4
  • 2 <= 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.