
Get ready for some hot content related to solving Hacker Rank problems. Spoiler alert: I will be discussing my solutions, so if you’re not looking for that, now you know.
Today let’s go over a subarray division problem. I’m not going to reproduce the entire problem, but the gist of it is that you need to take an array of integers, divide up the elements into subarrays that vary in length according to a given number (n), and find the number of subarrays that when summed together equal a given integer (x).
Time to go through this step by step. First, let’s name the function and figure out what we need to return.
function subarrays(array, n, x) {//array will need to be divided into subarrays of n length
//if the summed total of the subarray equals x, add one to the results variable let results = 0;
return results;}
The first issue to tackle is how to divide an array into smaller chunks given a variable length. Let’s say we have an array — [1,2,3,4] — and an integer, n, that tells us how long each subarray should be. If n is 2, the new array would look like this: [[1,2],[3,4]]. Using a while loop and the slice method on the original array, we can create a new array like so:
function subarrays(array, n, x) {
let results = 0;
let chunk = [];
let i = 0;
while (i < array.length) {
chunk.push(array.slice(i, n + i));
i++;
}
//return results
}
Notice that the subarrays are pushed into a new variable called chunk, which is initialized as an empty array. Also, it’s important to note that the arguments inside of the slice method are incremented as i increases, keeping in mind that n is the length of each subarray.
Now the easy part. Once the chunks are in place, simply using a forEach loop and summing each subarray with reduce will allow us to check if the total equals the last argument of the function, x. Here’s the rest of my solution:
function subarrays(array, n, x) {
let results = 0;
let chunk = [];
let i = 0;
while (i < array.length) {
chunk.push(array.slice(i, n + i));
i++;
};
chunk.forEach(nums => {
nums.reduce((a,b) => a + b) === x ? results++ : null;
});
return results;
};
And that’s it, friends. Thanks for reading! 🎉 🎉 🎉