Challenge with the Nested List Weight Sum algorithm

Trying to crack the challenge "Nested List Weight Sum":

Challenge:

If given the list [[1,1],2,[1,1]], the expected output is 10. (four 1's at depth 2, one 2 at depth 1)

Here's my approach.

function calculateDepthSum(nestedList, sum=0, depth=1) {
    nestedList.forEach((val) => {
        if (Array.isArray(val)) {
            depth = depth+1;
            return calculateDepthSum(val, sum, depth);
        } else {
            sum += val * depth;
        }
    });
    return sum;
};

Struggling with an issue in my code. It seems to almost work, but for some reason it's not returning the correct result when it should. Can anyone help me spot the bug?

Answer №1

One approach is to utilize the Array#reduce method and eliminate the need for a separate sum variable by calculating the sum for each level directly.

function depthSum(nestedList, level = 1) {
    return nestedList.reduce((sum, val) =>
        sum + (Array.isArray(val)
            ? depthSum(val, level + 1)
            : level * val),
        0);
};

console.log(depthSum([[1, 1], 2, [1, 1]]));

Answer №2

To approach this challenge in a different way.

Instead of returning from inside the forEach loop, it's more effective to add the total from the recursive call to your current total. By doing this, there's no need for the sum parameter in your depthSum function.

var nestedList = [[1,1],2,[1,1]];

var depthSum = function(nestedList, depth = 1) {
  var sum = 0;
  nestedList.forEach((val) => {
    if (Array.isArray(val)) {
      sum += depthSum(val, depth + 1);
    } else {
      sum += val * depth;
    }
  });
  return sum;
};

console.log(depthSum(nestedList))

Answer №3

Following the requirement of the code in Leetcode, here is the functional code:

    var calculateDepthSum = function (nestedList, depth=1) {
    var result = 0;
    nestedList.forEach((val) => {
        if (val.isInteger() === false) {
            result += calculateDepthSum(val.getList(), depth + 1);
        } else {
            result += val.getInteger() * depth;
        }
    });
    return result;
};

The use of Array.isArray() is not possible in this case as it will return false for all members. Direct access to values or lists is also prohibited. It is necessary to access them through their API. The function's input is not a simple array; refer to the input type and APIs from the specifications provided below:

     * function NestedInteger() {
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     @return {boolean}
 *     this.isInteger = function() {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     @return {integer}
 *     this.getInteger = function() {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     @return {void}
 *     this.setInteger = function(value) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and add a nested integer elem to it.
 *     @return {void}
 *     this.add = function(elem) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds, if it holds a nested list
 *     Return null if this NestedInteger holds a single integer
 *     @return {NestedInteger[]}
 *     this.getList = function() {
 *         ...
 *     };
 * };
 */
/**
 * @param {NestedInteger[]} nestedList
 * @return {number}
 */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I toggle the visibility of form inputs while utilizing Vue Formulate Schemas?

I've been experimenting with Vue Formulate schemas to build a form. My goal is to have two radio buttons, A and B, where clicking A reveals an additional input field below. When B is clicked, the extra input field should be hidden. Using a schema is ...

What is the best way to extract information from this JSON data?

I'm struggling to parse the following JSON successfully: [{ "id":10, "description":"Prueba", "name":"Prueba", "price":"3.5", "updated_at":"2013-06-10T13:41:25Z", "images": [{ "image":{ "id":6, "type ...

The networking feature stops functioning on Android devices after upgrading from Ionic 1.5.0 to 1.6.3

After upgrading from ionic 1.5.0 to 1.6.3 (the latest version), I noticed that networking ajax calls were no longer working on Android. I had to remove and re-add the android platform, and there seemed to be a change in the apk names from MainActivity-debu ...

C++ Troubleshooting: Issues with Initializing a Double Pointer

Apologies for not providing the full source code as I am working with a vast code-base. I will do my best to explain the issue in detail in hopes of receiving some insight into a solution. The problem arises when I attempt to create a pointer to a pointer ...

What is the process for changing the state of an array in graphql?

Currently, I am facing a challenge with adding an array to a GraphQl schema. Here is what it looks like: type Play { winRatio: [Float] } The intention behind the winRatio attribute is to store the history of all win ratios. For instance, after playing 3 ...

Interactive Bar chart updates in real-time with Highcharts and AngularJs

With the help of a sample from Highcharts (here), I successfully integrated a bar chart into AngularJs. Below is the HTML code: <!DOCTYPE html> <html ng-lang="en" ng-app="myModule"> <head> <meta charset="ISO-8859-1"> <script sr ...

Can you explain the distinction between setting abc.p as undefined versus deleting abc.p?

The variable abc is pointing to an object. What distinguishes abc.p = undefined from delete abc.p aside from their return values? ...

Interact with Circles Through Mouse Movements with d3.js Animation

I am currently utilizing the d3.js library and facing a challenge in meeting the client's requirements. The client has requested for "circles to turn black" and "follow" the mouse when hovered over. I am unsure if d3.js library supports such a featu ...

pythonAppending new rows to an empty 2D numpy array

Is there a way to populate an empty 2D numpy array with rows using a loop? yi_list_for_M =np.array([]) M =[] for x in range(6) : #some code yi_m = np.array([y1_m,y2_m]) yi_list_for_M = np.append(yi_list_for_M,yi_m) The current output is: [0. ...

Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS. My current setup In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js Additionally, I use a plugin ...

Best method for distributing components across nextjs zones?

Scenario: I am currently working on a project using Next.js and taking advantage of its multi zones feature. This feature allows us to run multiple independent NextJS applications as a unified app, managed by different teams. The Issue: One challenge I fa ...

PHP: Conversion of data types and modifying elements within a foreach loop

Today, I encountered a peculiar scenario. While trying to change an array element within a foreach loop, I was aware that it can be achieved using references. foreach((array)$output['subjectComposite'] as &$subjectComposite){ $subjectC ...

Resetting the state of toggle/click states in AJAX and jQuery

Currently, I am encountering a small dilemma with a .on function and AJAX in conjunction with a mobile menu. The mobile menu is located in the header of a site that relies heavily on AJAX for its content loading. This poses an issue because when an AJAX ca ...

Can you recommend a technology similar to WebSockets that does not rely on a framework like Node.js?

I am currently developing a basic betting game and I want to enhance the user experience by updating values in real-time. The challenge is that most of my application is written in jQuery and JavaScript, with a MySQL database set up by a different develo ...

Having trouble extracting the Top-Level Domain from a URL

I'm struggling to find a reliable way to extract the Top-Level Domain from a URL. The challenge I'm facing is that the URLs entered by users can vary greatly - they might enter www.google.com, m.google.com, m.google.uk, google.uk, or www.m.google ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

Refresh a specific DIV element without having to refresh the entire page

I have a Div Tag that includes Small.php to populate it with information. My goal is to refresh the content every 15 seconds without reloading the entire webpage. I've attempted using JavaScript/jQuery without success. <script type="text/javascrip ...

update embed - new command

My code below creates a slash command and I'm attempting to update the embed every 10 seconds. const embed = new EmbedBuilder() .setAuthor({ name: track.title, iconURL: client.user.displayAvatarURL({ size: 1024, dynamic: true }) }) .setThumbna ...

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

What is the best method to extract an array of values or rows from my grid layout?

Looking for a way to convert my CSS-grid into a CSV format. I came across a helpful thread outlining how to structure the data in an array: How to export JavaScript array info to csv (on client side)?. Is there a method to extract all the div values in th ...