Leetcode Problem 1590. Make Sum Divisible by P
1590. Make Sum Divisible by P
AI Mock Interview
Leetcode Solutions
Prefix Sum and HashMap
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Calculate the total sum of the array and find the remainder
need
when divided by
p
.
If
need
is 0, return 0 as the array sum is already divisible by
p
.
Initialize a hashmap to store the index of the last occurrence of a prefix sum modulo
p
.
Initialize variables for the current prefix sum and the minimum length of the subarray to remove.
Iterate through the array, updating the current prefix sum modulo
p
.
For each prefix sum, calculate the complement that would make the sum divisible by
p
.
Check if the complement exists in the hashmap. If it does, update the minimum length of the subarray to remove.
Update the hashmap with the current prefix sum modulo
p
.
After iterating through the array, check if the minimum length is less than the array size. If so, return it; otherwise, return -1.
Sliding Window
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...