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 a contiguous block of elements in the array.

30:00

Make Sum Divisible by P
medium
Free written solution
Topics
Companies

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 a contiguous block of elements in the array.

Example 1:
Input: {"nums":[3,1,4,2],"p":6}
Output: 1
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1091 \leq \text{nums}[i] \leq 10^9

  • 1≤p≤1091 \leq p \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,1,4,2],"p":6}

Add up every element: the sum is 10. Only its remainder mod 6 matters.

p 6
need = sum % p 4
cur -
want -

nums, with the prefix remainder (sum through that index) % p underneath

-1

start
0

0

3
·

1

1
·

2

4
·

3

2
·
■ current index■ prefix with remainder want, and the piece after it■ best piece so far

last: remainder → latest index

empty

no valid piece yet

best = -

Variables
VariableValue
p6
sum10
DepthFunction Call
Stack empty
0/15