Array Wrapper - Leetcode 2695 - JavaScript 30-Day Challenge

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

Key Takeaways

The video demonstrates how to solve the Array Wrapper problem on LeetCode by creating a class that overloads operators and functions in JavaScript, specifically using the reduce method to sum an array of numbers and converting an array to a string with custom formatting.

Full Transcript

hey everyone welcome back and let's write some more neat code today so they'll solve the problem array wrapper we are creating a class array wrapper even though they made it a function and basically the premise of the problem is that we want to overload a couple operators for this class and it's easier to understand when you take a look at the example so here you can see that we're creating two instances of the array wrapper class passing in an array of numbers each time that's always going to be the input for this class that's why it's called array wrapper and I guess we're guaranteed that it's going to be numbers as well like that's the type of this array what's happening is kind of interesting here if you've never seen this before we're literally taking the plus operation between these two objects and somehow we're getting a number as the result so that's pretty weird if you've never seen it before but this is actually pretty common in other languages like C plus plus which is the first language I learned I think you can also do it in Python but I'm not super familiar with doing this type of stuff in Python but one language you definitely can't do it in is Java because Java is a pretty rigid language it doesn't give you that flexibility but C plus probably gives you too much flexibility at least for certain cases in this case we're not technically overloading the plus operation we're not giving it a different meaning what we're actually doing is overloading the value of method on this object and we're doing that by adding to the Prototype so what JavaScript is going to do before executing this statement it's going to get the value of this and the value of that and then add them together now normally for just a regular number like five plus five the value is the same thing itself and I think it's probably similar when you're dealing with strings as well so what we really want to do is more this array convert it into a single number within this function and in our case they told us in the problem description that this number should evaluate to the sum of this array this number should evaluate to the sum of this array so that itself is pretty simple before I get into the second thing that we want to implement because it's completely different let's actually finish implementing this portion so in our class the first thing we want to do is given that array of numbers just set it to a member variable and we can do that like this so that's what's making this a class even though it's a function that's why we can call the new keyword here that will initialize this I would much prefer though to write this with class syntax because I think it makes it more obvious but oh well and now to get the value of that array remember we do have access to this dot nums within this method even though this is not directly defined inside of the array wrapper and for that particular array of numbers we want to get the sum now you can't just call like a math function like sum that would be too easy JavaScript gives us a ton of flexibility but I guess it doesn't want to give us like a utility function like that so the easiest way to probably get the sum of this array is by calling reduce on it if you remember how that works it's a good a chance to review that when you call reduce we pass send two things we pass in a function a callback so I'm just going to Define like an anonymous function here and the second parameter is the accumulator in our case we want to accumulate the sum of these numbers and the initial value for the accumulator can be set to zero so that's the second parameter here now for our function itself one of the parameters is going to be a number from this array I'm going to call it n and the second parameter is going to be the accumulator which yes the initial value is zero but I'm going to call it a for short and what we want to return after iterating through each number is basically the sum of that number plus the accumulator so far so this will pretty much get the entire sum of these numbers stored in the accumulator and it will also return that from the reduce method so we can go ahead and just return at this point and that will be the sum and so now when we try to execute this line of code down here it will work as expected but the next part is going to be a bit more into interesting well I would actually say it's a bit more straightforward when you convert a string to an object we can also overload that method as well I think this actually is available in Java so this will not be super complicated what they told us though we want to do is for that array we want to print it in this format you might think well then from here can we literally just say convert string for this number array and then return that well we can't because when you convert an array like this to a string we actually get one two we get that without the outer bracket so what we want to do to this is just add the brackets on the outside and the easiest way to do that is using back ticks or you could also add a character at the beginning and a character at the end but I'm just going to use back text so we'll have an Open Bracket we want to say this string nums is not a string it's actually a variable so we can do that with a dollar sign curly braces and then close this off with the closing bracket so it's really as simple as that now we could also take these two strings and concatenate them together but that's obviously not a part of the problem but you can imagine how overloading these types of operators could be helpful but to be honest most of the time you probably don't want to do this because it can get kind of complex now let's run the code to make sure that it can work of course there's a bug we don't have a reference to nums we need to use our current context which is using the this keyword so now hopefully this works now as you can see yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon

Original Description

Solving Day 28 of the Leetcode 30-day javascript challenge. Today we implement an array wrapper, but more specifically we overload some operators / functions of our class. 🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🥷 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-wrapper/ 0:00 - Read the problem 0:40 - Read examples 2:00 - Coding Solution leetcode 2695 #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

The video teaches how to create a class in JavaScript that overloads operators and functions to solve the Array Wrapper problem on LeetCode, demonstrating the use of the reduce method and custom string formatting.

Key Takeaways
  1. Create a class to overload operators and functions
  2. Use the reduce method to sum an array of numbers
  3. Convert an array to a string with custom formatting using backticks and template literals
  4. Implement the valueOf method to return the sum of the array
  5. Test the code to ensure it works as expected
💡 Operator overloading in JavaScript can be achieved by implementing the valueOf method in a class, allowing for custom behavior when using operators like + or when converting an object to a string.

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 (3)

Read the problem
0:40 Read examples
2:00 Coding Solution
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →