- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array nums and another value p, we remove the smallest subarray (not the whole array) such that the sum of the remaining values is divisible by p. We have to find the length of the smallest subarray that we need to remove, if there is no such subarray then return -1.

So, if the input is like nums = [8,2,6,5,3] p = 7, then the output will be 1 because if we remove 3, then total sum will be 21 and that is divisible by 7.

To solve this, we will follow these steps −

- ans := infinity
- s := (sum of all elements in nums) mod p
- d := a map contains key-value pair {0: -1}
- cum := 0
- if s is same as 0, then
- return 0

- for i in range 0 to size of nums, do
- cum := cum + nums[i]
- r := cum mod p
- if (r-s)mod p is present in d, then
- ans := minimum of ans and i - d[(r-s) mod p]

- d[r] := i

- return ans if ans < size of nums otherwise -1

Let us see the following implementation to get better understanding −

def solve(nums, p): ans = float("inf") s = sum(nums) % p d = {0:-1} cum = 0 if s == 0: return 0 for i in range(len(nums)): cum+=nums[i] r = cum%p if (r-s)%p in d: ans = min(ans, i-d[(r-s)%p]) d[r] = i return ans if ans<len(nums) else -1 nums = [8,2,6,5,3] p = 7 print(solve(nums, p))

[8,2,6,5,3], 7

1

- Related Questions & Answers
- Program to find length of smallest sublist that can be deleted to make sum divisible by k in Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Removing smallest subarray to make array sum divisible in JavaScript
- Greatest Sum Divisible by Three in C++
- Sum which is divisible by n in JavaScript
- Program to Find Out the Largest K-Divisible Subsequence Sum in Python
- C Program to check if a number is divisible by sum of its digits
- Python Program to check whether it is possible to make a divisible by 3 number using all digits in an array
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Python Program for Smallest K digit number divisible by X
- Count all sub-arrays having sum divisible by k
- Smallest Integer Divisible by K in Python
- Binary Prefix Divisible By 5 in Python
- Number of digits to be removed to make a number divisible by 3 in C++
- Python Program to Print all Numbers in a Range Divisible by a Given Number

Advertisements