#1590

Make Sum Divisible by P

Medium
ArrayHash TablePrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using prefix sums and a hashmap, we can efficiently find the smallest subarray to remove. This approach leverages the properties of remainders to minimize the number of checks needed.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the total sum of the array and its remainder when divided by p.
  2. 2Step 2: If the remainder is 0, return 0 (no need to remove anything).
  3. 3Step 3: Use a hashmap to track the first occurrence of each prefix sum remainder.
  4. 4Step 4: Iterate through the array, updating the prefix sum and checking if the current remainder can form a valid subarray.
  5. 5Step 5: If a valid subarray is found, update the minimum length of the subarray to remove.
solution.py18 lines
1# Full working Python code
2
3def minSubarray(nums, p):
4    total_sum = sum(nums)
5    remainder = total_sum % p
6    if remainder == 0:
7        return 0
8    prefix_sum = 0
9    min_length = float('inf')
10    remainder_map = {0: -1}
11    for i in range(len(nums)):
12        prefix_sum += nums[i]
13        current_remainder = prefix_sum % p
14        target_remainder = (current_remainder - remainder + p) % p
15        if target_remainder in remainder_map:
16            min_length = min(min_length, i - remainder_map[target_remainder])
17        remainder_map[current_remainder] = i
18    return min_length if min_length != float('inf') else -1

Complexity note: This complexity comes from a single pass through the array and maintaining a hashmap of remainders, making it much more efficient than the brute-force approach.

  • 1Understanding the relationship between the total sum and the subarray sum is crucial.
  • 2Using prefix sums and remainders can significantly reduce the number of checks needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.