Array Reduce Transformation (Transforms) - Leetcode 2626 - JavaScript 30-Day Challenge

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·3y ago

Key Takeaways

Solves Leetcode 2626 Array Reduce Transformation using JavaScript

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem array reduce transformation so we already talked about mapping and filtering but there's also another common function when it comes to functional programming and that is reducing conceptually it's similar to the other Transformations but in terms of using it it's a bit more complicated so that's what I'm going to be spending my time on in this problem first of all what even is reducing well it's all about aggregation let me actually show you what reducing is about let's say we're given this array and we want to find the sum of it well it's pretty easy to just pass this into like a library function and get the sum but I want to show you how we can do that with the reduce function that is built into arrays in JavaScript so we can say nums dot reduce this array but we have to actually tell it how we want to reduce the array how we want to aggregate this because aggregation can work in many ways we could be trying to find the total sum of this array or we could be trying trying to find the maximum value of this array the common theme here though is that we're given a list of values but we want to reduce them to a single value makes sense doesn't it now the function that we pass in to reduce has to kind of follow this header where it takes two parameters the first parameter is our initial value and the second parameter is going to represent a individual value from our list so what I mean here is when we take the sum of an array like this what do we want our initial value to be probably zero right so that's how we're going to call this function when we actually do pass it into reduce so let me actually do exactly that I'm going to pass in this function into reduce but we also have to pass in a second parameter to reduce to tell it what we want our initial starting value to be when we calculate the sum of this I'm going to initially set the starting value to zero now to actually fill in this function you might be getting the idea here this is going to be the initial value so what would we want to return if we're trying to take the total sum we probably can take the initial value and add it with n and then return that so what that would do for the first value is obviously 0 plus 1 and that's what it would return for just the first value here but then on the second iteration of the loop this is where something cool happens this function is going to be called again but it's not going to be past a zero for the initial value it's going to be passed in the previous value that we calculated which was one and if you take that one and add it with our current value n which is going to be 2 we get a 3 so then we would return 3 from here next we get to a seven so we take seven and add it with the previous value that we just calculated which was three so that's how this function is going to work but notice how most of that is abstract acted for us that's kind of the power behind functional programming we don't have to manage our own State we don't have to iterate through this list and just to prove to you that this works let me go ahead and console log it and as you can see the result is 19 as we would expect so now that we know a little bit about reduce let's actually solve the problem so the most trivial way to solve this problem is just to take the list of nums call reduce on them passing in whatever function we are given because that's how we want to reduce this with this initial value so basically that's what they were trying to teach us how reduce works even though they told us we're not allowed to use it but don't worry I'll solve it the imperative programming way in just a second let's run this to make sure that it works it does but there are other solutions to solve this problem so let's take a look let's recreate what this is actually doing explicitly we know initially our result is going to be whatever that initial value happens to be passed in and then we know we want to go through every single number in the input array nums take a second to think how you iterate through each number in an array well in Python we can use the keyword of that's usually the easiest way so for const n of nums in this case we don't need the index so we don't need the keyword in and with each value we just want to call that function and depending on which aggregation we're doing we could honestly pass in n and the initial value in either order but technically the correct order to pass it in is to pass in the initial value first and then pass in the current value that we're at in our list and then we would call this function and then update our result with that value but notice there is a small bug here when we call the function we don't want to pass in the initial value every single time I know that's a bit misleading because based on this over here on the left it kind of seems like we do but let's say the initial value is zero we don't want to keep adding zero with each element in the array we want to add the previous result which is over here thankfully stored in a variable and add that with n so I'm going to pass in the result into this function which initially is the initial value so it does work out for us after that's done I'm going to go ahead and return the result and run this to make sure that it works as you can see yes it does but there's one last Quick solution it's kind of a halfway solution between this reducing functional programming solution and this like fully imperative solution I guess not entirely imperative because we could have actually iterated through this with an index that we like explicitly increment but I'm sure you already know how to do that so I won't bother with it too much the other way to solve this problem would be to take uh let me erase this that list of nums and there's another function that belongs to every list it's called for each and basically it'll call some function that we pass into it on each element in the array so how can this be used to solve this problem well first let's pass in a function I'm going to pass in an anonymous function which we can do just like this we have our parameters here which parameter are we passing in well we're going to go through each number so I'm going to have n for each number in the input and this is our block what do we want to return well in this case we don't really need to return anything we just need to update our outside State we need to update our result value by setting it equal to the function being called with the result and the individual value that we're currently at after running this our result variable will be updated so we can go ahead and run this to make sure that it works and as you can see yes it does but I guess it's a little bit slower those are all the solutions I wanted to discuss you might be starting to see the power of functional programming or maybe you're starting to hate it I don't know but thanks for watching if you found this helpful please like And subscribe and hopefully I'll see you pretty soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews Solving day 6 of leetcode's 30-day javascript challenge. Today we continue with functional programming concepts using the Reduce operation. 🥷 Discord: https://discord.gg/ddjKRXPqtk 🐦 Twitter: https://twitter.com/neetcode1 🐮 Support the channel: https://www.patreon.com/NEETcode ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf 💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1 Problem Link: https://leetcode.com/problems/array-reduce-transformation/ 0:00 - Read the problem 0:30 - Built-in Reduce usage 3:15 - Reduce solution 3:45 - For-loop solution 5:22 - For-each solution leetcode 2626 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (5)

Read the problem
0:30 Built-in Reduce usage
3:15 Reduce solution
3:45 For-loop solution
5:22 For-each solution
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →