Make Sum Divisible by P

Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.

Return the length of the smallest subarray that you need to remove, or -1 if it is impossible.

A subarray is defined as a contiguous block of elements in the array.

Example 1
Inputnums = [3,1,4,2], p = 6
Output1
The sum of the elements in nums is 10, which is not divisible by 6, so removing [4] leaves a sum of 6, which is divisible by 6.
Example 2
Inputnums = [6,3,5,2], p = 9
Output2
A single element cannot be removed to make the sum divisible by 9, but removing [5,2] leaves [6,3] with sum 9.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= p <= 10^9

Asked at 7 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate