Make Sum Divisible by P — LeetCode 1590 Python Solution

MediumArrayHash TablePrefix Sum
Problem
#1590
Pattern
Prefix Sum
Reading time
3 min

The problem

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.

Example

Input
nums = [3,1,4,2], p = 6
Output
1
Explanation
The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.

Python solution

Python
class Solution:
    def minSubarray(self, nums: List[int], p: int) -> int:
        k = sum(nums) % p
        if k == 0:
            return 0
        last = {0: -1}
        cur = 0
        ans = len(nums)
        for i, x in enumerate(nums):
            cur = (cur + x) % p
            target = (cur - k + p) % p
            if target in last:
                ans = min(ans, i - last[target])
            last[cur] = i
        return -1 if ans == len(nums) else ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1590. Make Sum Divisible by P is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1590. Make Sum Divisible by P?
LeetCode 1590. Make Sum Divisible by P is rated Medium on LeetCode.
What is the time complexity of LeetCode 1590. Make Sum Divisible by P?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1590. Make Sum Divisible by P?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1590. Make Sum Divisible by P cover?
LeetCode 1590. Make Sum Divisible by P is tagged Array, Hash Table and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview