Make Sum Divisible by P (LeetCode 1590): Solution and Explanation

Medium
Array
Hash Table
Prefix Sum

Remove the shortest contiguous piece so the rest sums to a multiple of p. The piece must carry the leftover remainder need = sum % p, and prefix remainders stored in a hash map find the shortest such piece in one pass.

Intuition

If the total leaves remainder need when divided by p, the remaining elements are divisible by p exactly when the removed piece also leaves remainder need. So the task becomes: find the shortest subarray whose sum is congruent to need modulo p.

A subarray sum is a difference of two prefix sums. Taken modulo p, the piece from j + 1 to i has remainder need when prefix[i] - prefix[j] is congruent to need, which means prefix[j] has remainder (prefix[i] - need) mod p.

So while scanning, keep a map from each prefix remainder to the latest index where it appeared. At index i, look up the remainder you want. The latest index gives the shortest piece ending at i.

Approach: Prefix remainders with a latest-index map

  1. Compute need = sum(nums) % p. If need is 0, return 0.
  2. Put remainder 0 at index -1 in the map, for pieces that start at index 0.
  3. Scan i from left to right, keeping cur = prefix remainder through i.
  4. Let want = (cur - need) mod p. If want is in the map, the piece from last[want] + 1 to i works; update best with its length.
  5. Store last[cur] = i, overwriting any older index.
  6. If best is still n, only the whole array works, which is not allowed: return -1. Otherwise return best.

Step-by-step example

nums = [3,1,4,2], p = 6
  1. The sum is 10, so need = 10 % 6 = 4. Map: {0: -1}.
  2. i = 0: cur = 3, want = (3 - 4) mod 6 = 5, not in the map. Store 3 -> 0.
  3. i = 1: cur = 4, want = 0, found at -1. Piece nums[0..1] has length 2, best = 2. Store 4 -> 1.
  4. i = 2: cur = 8 % 6 = 2, want = 4, found at 1. Piece nums[2..2] = [4] has length 1, best = 1. Store 2 -> 2.
  5. i = 3: cur = 4, want = 0, found at -1, length 4, not better. Return 1.

Code: Python, Java, C++

1class Solution:
2    def minSubarray(self, nums: List[int], p: int) -> int:
3        need = sum(nums) % p
4        if need == 0:
5            return 0
6        last = {0: -1}
7        best = len(nums)
8        cur = 0
9        for i, x in enumerate(nums):
10            cur = (cur + x) % p
11            want = (cur - need) % p
12            if want in last:
13                best = min(best, i - last[want])
14            last[cur] = i
15        return best if best < len(nums) else -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass to get the sum and one pass with constant-time map operations.

Space

O(min(n, p))

The map holds at most one entry per distinct prefix remainder.

Other approaches

Check every subarray (time O(n^2), space O(1))

For each start, extend the end while tracking the piece's remainder and keep the shortest that equals need. Simple but too slow for 10^5 elements.

Same idea with a two-pass map (time O(n), space O(n))

Precompute all prefix remainders into an array first, then run the lookup pass. It is the same algorithm with an extra O(n) array.

Common mistakes

  • Forgetting the entry 0 -> -1, which misses pieces that start at index 0.
  • Returning n when the only valid piece is the whole array. Removing everything is not allowed, so that case is -1.
  • Computing (cur - need) % p in Java, C++, C# or JavaScript without adding p, which gives a negative key.
  • Summing all elements into a 32-bit int. The total can reach 10^14, so reduce modulo p as you go or use a 64-bit type.
  • Keeping the first index of each remainder instead of the latest, which finds longer pieces.

Frequently asked questions

Why store the latest index rather than the first?

The piece ending at i starts right after the stored index. A later index means a later start and therefore a shorter piece.

Why is removing the whole array treated as -1?

The problem forbids it. The whole array always has remainder need, so best = n would always be available; it must be rejected at the end.

Does the order of the lookup and the store matter?

Here it does not, because need is not 0 inside the loop, so want never equals cur. Looking up first still reads more naturally: only earlier prefixes are candidates.

How is this related to Subarray Sums Divisible by K?

Both use prefix remainders in a hash map. That problem counts pieces with remainder 0; this one finds the shortest piece with remainder need.