
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Remove Smallest Subarray to Make Array Sum Divisible in JavaScript
We are required to write a JavaScript function that takes in an array of positive integers as the first argument and a positive integer as the second argument.
The function should figure out and return the length of the smallest subarray that we should delete from the original array in order to make its sum divisible by the number specified by the second argument.
For example −
If the input is −
const arr = [3, 8, 2, 6]; const num = 9;
Then the output should be −
const output = 2
Because the subarray that needs to be deleted is [8, 2]
Example
Following is the code −
const arr = [3, 8, 2, 6]; const num = 9; const minimumDeletion = (arr = [], num) => { const diff = arr.reduce((a, b) => a + b) % num; let res = diff == 0 ? 0 : arr.length; for (let i = 0, sum = 0, map = {0: -1}; i < arr.length; i++) { sum += arr[i]; const target = (sum % num - diff + num) % num; if (map[target] != undefined) { res = Math.min(res, i - map[target]); }; map[sum % num] = i; }; return res == arr.length ? -1 : res; }; console.log(minimumDeletion(arr, num));
Output
Following is the console output −
2
Advertisements