DEV Community

Shubham_Baghel
Shubham_Baghel

Posted on

1

LeetCode Two Sum problem Solution in JavaScript

Two Sum
LeetCode Link:[https://leetcode.com/problems/two-sum/]

Problem Statement:
Given an array of integers Nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Solution:
1.Brute Force:
In this approach we are iterating array with two loops where we are checking sum of first and next element with target if it matches then we are returning index of element. But in this case Time complexity will be O(NĀ²)

Code:
Brute Force Approach

2.Map based Approach
This solution is more optimize as we are using map and just checking finding out the required element which will be subtracted from current num of array. Here we are checking that element is present in map or not using Map.has() method.(Read more about Map.has() method of Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has)
In Nutshell, We can utilize a HashTable to search for the required elements with pair.

Code:
Optimize Approach

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay