Conquer the JavaScript Interview: Cumulative Sum [Beginner Skill Level]

preview_player
Показать описание
Link to this Playlist:

This is a part of my Algorithms and Data Structures playlist series. We cover a lot of common interview questions asked during whiteboards for entry level developers. Learning to master these takes time, practice, and pattern recognition. So I'll be helping you equip a toolbelt and filling it with as many tools as I can to help prepare you crush those interviews! Remember: "Luck is where practice meets opportunity."

In this video we go over the cumulative sum algorithm. We declare a function called cumulativeSum that takes an array of integers, arr, as its argument. We initialize an empty array called result to store the cumulative sums. Then we initialize a variable called sum with a value of 0 to keep track of the current cumulative sum. From there, we simply Iterate through the input array, arr, using our good friend the for loop. For each element in the input array, add its value to sum, and then push the updated value of sum to the result array. Return the result array containing the cumulative sums. Nothin' to it!

Even as simple as this is, remember it is a building block for more complex algorithms: The cumulative sum algorithm can be a building block for more complex algorithms and tasks, such as calculating running averages, moving averages, or other statistical measures. It can also be used as a preprocessing step for problems related to dynamic programming or data analysis.

Don't forget to like this video and subscribe to our channel – we're publishing more videos and walkthroughs every week. Comment below and let us know what you'd like to see next!

#algorithms #javascript #interview #interviewtips #cumulative
Рекомендации по теме
Комментарии
Автор

Here's how I would do it without a sum variable, I think this approach is called "dynamic programming"

function cumulativeSum(arr) {
const result = new Array(arr.length).fill(0);
result[0] = arr[0];

for(let i=1;i<arr.length;i++) {
result[i] = result[i-1] + arr[i];
}

return result;
}

In theory this way might be faster with a large arr because we are allocating an array in advance instead of pushing values and the array being resized over and over

soniablanche
welcome to shbcf.ru