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Ā²)
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.
Top comments (0)