Make Sum Divisible by P
Real-world version: Shortest Run to Pull From the LoadThe statement here is our own: the same inputs, outputs and technique.
A freight car is loaded with pallets in a single row, and nums[i] is the weight of the pallet in position i. The yard will only release the car when the total weight on board is a multiple of p.
You may pull out one unbroken run of pallets, and only one. You may also pull out nothing at all. You may not pull out every pallet: at least one pallet has to stay on board.
Return the length of the shortest run you can pull out so that the weight left on board is a multiple of p. If no choice of run works, return -1. Pulling out nothing counts as a run of length 0.
Examples
Example 1
- Input
- nums = [9, 2, 6, 4, 5], p = 11
- Output
- 1
The load weighs 26, which is not a multiple of 11. Pulling out the single pallet in position 3, weight 4, leaves 22 on board, and 22 is 11 twice over.
Example 2
- Input
- nums = [5, 5, 5], p = 7
- Output
- -1
The load weighs 15. The runs available are of weight 5, 5, 5, 10 and 10, and none of them leaves a multiple of 7 behind. Pulling out all three pallets would leave 0, which is a multiple of 7, but the car may not be emptied.
Example 3
- Input
- nums = [1, 2, 3], p = 1
- Output
- 0
Every whole number is a multiple of 1, so the load already qualifies and nothing has to come off.
Constraints
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^9
- 1 <= p <= 10^9
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def min_subarray(nums: list[int], p: int) -> int:public int minSubarray(int[] nums, int p)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Check if All the Integers in a Range Are CoveredReal-world version: Patrol Coverage AuditEasy
- Subarray Sum Equals KReal-world version: Trail Elevation StretchesMedium
- Contiguous ArrayReal-world version: Balanced Shift StretchMedium
- Count Number of Nice SubarraysReal-world version: Runs With K Odd ReadingsMedium