Leetcode Problem 1590. Make Sum Divisible by P

1590. Make Sum Divisible by P

Leetcode Solutions

Prefix Sum and HashMap

  1. Calculate the total sum of the array and find the remainder need when divided by p.
  2. If need is 0, return 0 as the array sum is already divisible by p.
  3. Initialize a hashmap to store the index of the last occurrence of a prefix sum modulo p.
  4. Initialize variables for the current prefix sum and the minimum length of the subarray to remove.
  5. Iterate through the array, updating the current prefix sum modulo p.
  6. For each prefix sum, calculate the complement that would make the sum divisible by p.
  7. Check if the complement exists in the hashmap. If it does, update the minimum length of the subarray to remove.
  8. Update the hashmap with the current prefix sum modulo p.
  9. After iterating through the array, check if the minimum length is less than the array size. If so, return it; otherwise, return -1.
UML Thumbnail

Sliding Window

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...