

- 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
Removing 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
- Related Questions & Answers
- Maximum subarray sum in circular array using JavaScript
- Smallest positive value that cannot be represented as sum of subarray JavaScript
- Maximum sum subarray removing at most one element in C++
- Program to make sum divisible by P in Python
- Smallest number after removing n digits in JavaScript
- Program to find length of smallest sublist that can be deleted to make sum divisible by k in Python
- Path with smallest sum in JavaScript
- Check for Subarray in the original array with 0 sum JavaScript
- Left right subarray sum product - JavaScript
- Adding elements to array to make its sum diverse in JavaScript
- Checking digit sum of smallest number in the array in JavaScript
- Maximum contiguous sum of subarray in JavaScript
- Removing letters to make adjacent pairs different using JavaScript
- Maximize the maximum subarray sum after removing at most one element in C++
- Removing Negatives from Array in JavaScript
Advertisements