DEV Community


Posted on

LeetCode Two Sum problem Solution in JavaScript

Two Sum
LeetCode Link:[]

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.

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²)

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
In Nutshell, We can utilize a HashTable to search for the required elements with pair.

Optimize Approach

Top comments (0)