Back from where it came, the return function appears unable to escape the confines of the code

Currently, I am working on solving some leetcode problems and stumbled upon an interesting issue in my code for the problem at . However, I am having trouble understanding how it actually functions.

The problem with this code lies in the fact that the return statement in hasSimularArray does not exit from the function when called within the threeSum function. It seems like hasSimularArray keeps running as if it is a recursive function even though it's not. Thus, when it reaches the line "return true;" in hasSimularArray, it should stop executing the code within the function.

function threeSum(nums: number[]): number[][] {
  const tripletsResult = [];

  nums.sort((a, b) => a - b);

  for (let i = 0; i < nums.length - 2; i++) {
    let j = i + 1;
    let k = nums.length - 1;
    while (j < k) {
      const possibleResultEl = [nums[i], nums[j], nums[k]];
      const threeNumsSum = nums[i] + nums[j] + nums[k];
      if (threeNumsSum === 0) {
        const hasVal = hasSimularArray(tripletsResult, possibleResultEl);
        if (!hasVal) {
          tripletsResult.push(possibleResultEl);
        }
      } else if (threeNumsSum < 0) {
        j++;
      } else {
        k--;
      }
    }
  }

  return tripletsResult;
}

function hasSimularArray(mainArr: number[][], searchedArr: number[]) {
  if (mainArr.length === 0) {
    return false;
  }

  const searchArrayStr = JSON.stringify([...searchedArr].sort());
  for (let el of mainArr) {
    const elArrayStr = JSON.stringify([...el].sort());
    if (elArrayStr === searchArrayStr) {
      return true;
    }
  }
  return false;
}
console.log(threeSum([0, 3, 0, 1, 1, -1, -5, -5, 3, -3, -3, 0]));

Previously, I encountered a similar issue but with a slightly different code structure and the same return logic in a nested function. Surprisingly, the return statement not only exited from the nested function but also from the parent one.

I attempted to debug the code to understand what was happening behind the scenes, but unfortunately, it did not provide any clear insights.

In another scenario, when I tested hasSimularArray independently without the parent function using the same values, it worked correctly.

Could anyone shed some light on what is going wrong here?

Answer №1

The function hasSimularArray does not include a return statement

It appears that there may be a misunderstanding regarding the return statements within the function hasSimularArray. The issue here is not with the execution of these statements but rather with the functionality of the code itself.

Upon closer inspection, it is evident that the code enters an infinite loop when the condition threeNumsSum === 0 is met without adjusting the values of j or k, resulting in repeated iterations with the same parameters.

To resolve this, it is essential to modify the while loop by narrowing the window defined by (j, k):

When threeNumsSum equals 0, both j and k should be updated as follows:

      if (threeNumsSum === 0) {
        const hasVal = hasSimularArray(tripletsResult, possibleResultEl);
        if (!hasVal) {
          tripletsResult.push(possibleResultEl);
        }
        // Narrow the window!
        j++; 
        k--;
      }

Answer №2

When the array nums is significantly large, your algorithm might encounter crashes and failures.

To efficiently track which triplets have already been discovered, you can employ an Object (or alternatively a Map). This same object can be used to store the triplets that are intended for return.

function threeSum(nums: number[]): number[][] {
  const dupeTracker = {};

  nums.sort((a, b) => a - b);

  for (let i = 0; i < nums.length - 2; i++) {
    let j = i + 1;
    let k = nums.length - 1;
    while (j < k) {
      const sumOfThreeNums = nums[i] + nums[j] + nums[k];
      if (sumOfThreeNums === 0) {
        const possibleResultEl = [nums[i], nums[j], nums[k]];
        const uniqueKey = JSON.stringify(possibleResultEl.sort());
        if (!dupeTracker[uniqueKey]) {
          dupeTracker[uniqueKey] = possibleResultEl;
        }
      } else if (sumOfThreeNums < 0) {
        j++;
      } else {
        k--;
      }
    }
  }

  return Object.values(dupeTracker);
}

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

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

Cease the form submission process using Ajax when the input field is blank

I have implemented an ajax code that halts the form submission process if any input value is empty and displays a popup alert. However, I am facing an issue where the process continues even after closing the alert popup. How can I ensure that the process ...

Is it possible to send arguments to a debounced function using _.lodash?

Utilizing _lodash.debounce() has been a bit of a challenge for me. While I have managed to get it working, I can't help but feel that there might be a better way to implement it. The examples provided on the lodash website are quite basic and don&apos ...

Error encountered: Attempting to use a class as a function in vue-socket.io is not permitted

I am developing a Vue chrome extension where I am attempting to implement web sockets using vue-socket.io. I have followed the basic instructions on deploying a node server with express and socket.io on Heroku, but I am encountering issues with the conne ...

Tips for updating the front end with the status of a lengthy playwright test

In the node backend, I have defined a route for test progress using SSE (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). The URL initialization is happening on the frontend. Below is the code snippet from th ...

Encountering an "AJAX not a function" error while using the d3/flask interface

Hey there! I'm new to the world of JavaScript and AJAX. Take a look at this d3 function I've been working on: var node = g.selectAll(".node") .data(root.descendants()) .enter().append("g") .attr("class", function(d) { return "node" + ...

Utilizing JavaScript and JSON to Retrieve Array Elements by Key Names as Indexes

I'm looking for a way to access elements in an array using unique key names instead of numerical indexes. Specifically, I'm developing a Discord bot where each server has its own settings. When a message is sent on a server, I need to retrieve th ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

Sharing golang gin session with next.js

Utilizing the latest version of Next.js v14.2.3 and App Router. I am currently implementing cookie-based sessions from the gin-contrib documentation, in order to increase a session count. // Backend Golang code snippet ... cookieStore := sessi ...

Tips for displaying a Bootstrap 5 popover triggered by a select option change event

I'm using a select box with 4 options, and I have set it up so that when the user clicks on one of the options, a Bootstrap 5 popover is triggered dynamically upon the change event. Fiddle: https://jsfiddle.net/mayursutariya93/qjeg5r9b/6/ Here' ...

Removing a SubDocument from an Array in Mongoose

For my project, I am utilizing mongoose to create a database. The schema for my Class looks like this: const mongoose = require('mongoose') const classSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, consultant: { type: mo ...

What is the best way to implement a front-end CSS style for text instead of a background style?

I have HTML text I want to style with a color like rgba(0,0,0,0.1), but I want the color to appear above or on top of the text, not below or behind it. Issue: How can I accomplish this? (CSS or JavaScript solutions are welcome). Thank you in advance for ...

Arrange the colors in a predetermined sequence within the array

I am looking to implement a loop through an array and assign specific colors to each array element based on a predetermined order. Elements at positions first, fifth, ninth, and so on should be colored in red. Elements at positions second, sixth, tenth, a ...

How can Mui typescript be extended with a unique wrapper that includes a `component` property?

I recently created a unique wrapper component: import Box, { BoxProps } from "@mui/material/Box"; type CustomWrapperProps = { id: string } & BoxProps const CustomWrapper = (props: CustomWrapperProps) => { const {id, children, ...rest ...

Retrieving Book Title using Google Books API and ISBN

As a newcomer to Javascript and React-Native, I am in the process of developing a simple app that scans book barcodes for their ISBN numbers and matches them with their titles. Despite successfully retrieving the ISBN number, I am encountering an issue whe ...

Transforming jQuery into Angular - Press Button to update choices in Dropdown List

I am looking to integrate some AngularJS features into a website that currently utilizes jQuery. Here is the issue I am facing: With jQuery, clicking a button triggers a dropdown item change. Please refer to the jsfiddle below for an example: $('# ...

Using Object.freeze does not freeze the elements within an array

When I execute the following: var test = { 'test': 5 }; Object.freeze(test); // Throws an error test.test = 3; An error is thrown (as expected), but when I try this instead var nestedTest = [ {'test': 5}, {'test&ap ...

Learn how to create a disappearing dropdown menu in React that closes automatically when you select a specific category

I'm encountering an issue with a dropdown menu that remains visible on the screen even after selecting a specific category. The selected category is displayed in a box upon selection, but the dropdown menu doesn't disappear as intended. I am look ...

Is it possible to send two parameters to a JavaScript function using HTML?

Seeking help to develop an .html page where two string inputs are passed as parameters to a .js function, which then returns the longer of the two strings based on their lengths. Initially, I successfully created a functional .js script in VS CODE. Here i ...