Ctrl K

Trim to a Divisible Sum

Medium
You get an array of positive integers values and a number divisor. You may cut out one contiguous stretch of the array (possibly empty), but not the entire array. Find the length of the shortest such stretch whose removal leaves a sum divisible by divisor. If that is impossible, return -1.
Example 1
values=[4, 7, 2, 5], divisor=5 → 3

The total is 18. No single element leaves a multiple of 5, and neither does any pair (removing 11, 9 or 7 leaves 7, 9 or 11). Removing [4, 7, 2] leaves 5, so the answer is 3.

Example 2
values=[6, 1, 8], divisor=7 → 1

The total is 15; removing the 1 leaves 14.

Example 3
values=[3, 3], divisor=4 → -1

Removing one 3 leaves 3, and removing both is not allowed, so the answer is −1.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁹
  • 1 ≤ divisor ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Run with a Given Sum MediumA Stretch Divisible by k MediumAs Many Heads as Tails MediumStretches With an Exact Total MediumWindows With an Exact Alarm Count Medium
loading Python…
Input
values=[4, 7, 2, 5], divisor=5
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 68 tests on the server, hidden ones included.