The problem of finding the sum of two numbers always results in an empty

This function always results in an empty array.

Here is a JavaScript implementation for solving the two sum problem:

function twoSum(nums, target) {
  const map = {};

  for (let i = 0; i < nums.length; i++) {
    let comp = target - nums[i];
    if (map[comp] !== undefined) {
      return [map[comp], i];
    } else {
      map[comp] = i;
    }
  }
  return [];
}

console.log(twoSum([2, 7, 11, 15], 9));

Answer №1

Kindly review the information provided below:

  1. Save each number along with its corresponding index in a map, rather than the complement
  2. Determine if the complement is present in the map, not the actual number
  3. Output the indices of the numbers, not the numbers themselves
function findTwoSum(nums, target) {
    const numsMap = {};
    for(let i = 0; i < nums.length; i++) {
        const num = nums[i];
        const complement = target - num;
        if(numsMap[complement] !== undefined) {
            return [numsMap[complement], i];
        }
        numsMap[num] = i;
    }
}
const nums = [2,7,11,15];
const target = 9;

const resultIndices = findTwoSum(nums, target);
console.log(resultIndices); // [0,1]

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

Iterate through intricate array structures using the most efficient approach and minimal complexity

I have a scenario where I need to call an API that returns data in the following format: [{ Id: string, Value: string, Value2: [{Id: string, Value3: string}] , { Id: string, Value: string, Value2 ...

Is it possible to convert MUI components into strings on the client side?

I have incorporated the Material UI (MUI) library into my React application and am currently attempting to display certain components as PDF files directly in the browser. The approach I am taking involves: Creating a React element Rendering the React el ...

When employing TypeScript, an error pops up stating "cannot find name 'ObjectConstructor'" when attempting to use Object.assign

I am rephrasing my query as I realized it was unclear earlier. I have an API that is sending me data in the following format: {"photos":[{"id":1,"title":"photo_1_title"}]} In my code, I have a variable called photos and a function named getPhotos() For ...

Mask input in AngularJS

I am currently working on developing a custom directive for creating personalized masks for input fields. While there are other libraries available, I often need to create specific input formats tailored to the company's requirements (e.g., "OS.012-08 ...

What is the best way to extract information from an embed?

As I work on creating a suggestion command, I am faced with the challenge of editing the message with a "-approve <The message id>" command. The issue arises when attempting to retrieve information from the message using: const Suggestionchannel = cl ...

Enhance the appearance of the activated header - Ionic 3 / Angular 5

On the current page, I want to emphasize the title by underlining it or changing its color - something that clearly indicates to the user which page they are on. Currently, I am utilizing lazy loading for navigating between pages, using modules for each pa ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Is it possible for the Jquery Accordion to retract on click?

Hello everyone, I've created an accordion drop-down feature that reveals content when the header of the DIV is clicked. Everything works fine, but I want the drop-down to collapse if the user clicks on the same header. I am new to JQUERY and have trie ...

Tips for replacing spaces with &nbsp; in a string using ReactJS and displaying it in HTML

<div className="mt-2 font-sidebar capitalize"> {item.title} </div> item.title can vary and be any string retrieved from the backend, such as "all products", "most liked", "featured items", etc. I am looking for a solution to subst ...

Transferring data to a view

I have a dilemma with handling user selections from a select option list and a jstree object in Django. My goal is to pass these choices to a Django view for processing and obtain a response. I've encountered an issue where the template fails to load, ...

In JavaScript, obtaining the URL of an iframe after it has been reloaded is not functioning correctly in Chrome and Safari browsers

I have been developing a phaser game that will be integrated into a website through an iframe. The game has the capability to support multiple languages, and we have decided to determine the language based on the site from which the game was accessed (for ...

Guide on hiding a div element when clicked outside of it?

How can I create a dropdown feature in Khan Academy where it disappears when clicked outside but stays visible when clicked inside, using JavaScript/CSS/HTML? The current implementation closes the dropdown even on internal clicks. The code includes an even ...

Creating a customized image modal in ReactJS that incorporates a dynamic slideshow feature using the

I am attempting to incorporate an image lightbox into my React application: https://www.w3schools.com/howto/howto_js_lightbox.asp Here is the link to the CodeSandbox where I have tried implementing it: https://codesandbox.io/s/reactjs-practice-vbxwt ...

Enhancing mongoose find queries in Node.js with dynamic conditions using both AND and OR operators simultaneously

I've been experimenting with adding dynamic conditions using the Mongoose library. var and_condition = { $and: [] }; var or_condition = { $or: [] }; and_condition.$and.push ({ "doc_no" : /first/i }) or_condition.$or.push ({ "doc_type" : /third/i } ...

Illustrating an image in React-Admin sourced from a local directory with the path extracted from mongoDB

When pulling data from my mongoDB server, I'm encountering an issue with displaying the image. Everything else shows up correctly, except for the image. <ImageField source='filename' title="image" /> The filename in question ...

In React, the error message "Joke.map is not a function" indicates that

export default App I am encountering an error in this code which says joke.map is not a function. Can someone please assist me in finding a solution? I have verified the api endpoints and also checked the function. import { useEffect, useState } from &ap ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...

Discovering the property name of an object in Angular using $watch

Is there a way to monitor an object for changes in any of its properties, and retrieve the name of the property that changed (excluding newValue and oldValue)? Can this be accomplished? ...

Performing a function inside a JSON structure

I am dealing with a JSON object that contains a list of functions I need to access and run like regular functions. However, I'm struggling to figure out how to achieve this. Here is what I have attempted: Bootstrapper.dynamic = { "interaction": f ...

Serverside NodeJS with Socket.io experiencing issue with event communication from client

While attempting to set up a basic NodeJS server and Socket.io client for testing purposes involving WebSockets, I encountered an issue that seems rather silly. It's likely something silly that I've overlooked, considering I have previous experie ...