Skip to content

1590. Make Sum Divisible by P 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int minSubarray(vector<int>& nums, int p) {
    const long sum = accumulate(nums.begin(), nums.end(), 0L);
    const int remainder = sum % p;
    if (remainder == 0)
      return 0;

    unordered_map<int, int> prefixToIndex{{0, -1}};
    int ans = nums.size();
    int prefix = 0;

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i];
      prefix %= p;
      const int target = (prefix - remainder + p) % p;
      if (const auto it = prefixToIndex.find(target);
          it != prefixToIndex.cend())
        ans = min(ans, i - it->second);
      prefixToIndex[prefix] = i;
    }

    return ans == nums.size() ? -1 : ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int minSubarray(int[] nums, int p) {
    final long sum = Arrays.stream(nums).asLongStream().sum();
    final int remainder = (int) (sum % p);
    if (remainder == 0)
      return 0;

    int ans = nums.length;
    int prefix = 0;
    Map<Integer, Integer> prefixToIndex = new HashMap<>();
    prefixToIndex.put(0, -1);

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i];
      prefix %= p;
      final int target = (prefix - remainder + p) % p;
      if (prefixToIndex.containsKey(target))
        ans = Math.min(ans, i - prefixToIndex.get(target));
      prefixToIndex.put(prefix, i);
    }

    return ans == nums.length ? -1 : ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def minSubarray(self, nums: list[int], p: int) -> int:
    summ = sum(nums)
    remainder = summ % p
    if remainder == 0:
      return 0

    ans = len(nums)
    prefix = 0
    prefixToIndex = {0: -1}

    for i, num in enumerate(nums):
      prefix += num
      prefix %= p
      target = (prefix - remainder + p) % p
      if target in prefixToIndex:
        ans = min(ans, i - prefixToIndex[target])
      prefixToIndex[prefix] = i

    return -1 if ans == len(nums) else ans