
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
Subarray Sum with At Least Two Elements in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of Integers, arr, as the first argument and a single Integer, target as the second and first argument. Our function should check whether there exists a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n can be any integer.
We return true if it exists, false otherwise.
For example, if the input to the function is −
const arr = [23, 2, 6, 4, 7]; const target = 6;
Then the output should be −
const output = true;
Output Explanation:
Because [23, 2, 6, 4, 7] is a continuous subarray of size 5 and sums up to 42.
Example
The code for this will be −
const arr = [23, 2, 6, 4, 7]; const target = 6; const checkSubarraySum = (arr = [], target = 1) => { let sum = 0 const hash = {} hash[0] = -1; for (let i = 0; i<arr.length; i++) { sum += arr[i] if (target!=0) sum %= target if ( hash[sum] !== undefined ) { if(i-hash[sum]>1) return true } else { hash[sum] = i } }; return false; }; console.log(checkSubarraySum(arr, target));
Output
And the output in the console will be −
true
Advertisements