DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on • Edited on

Leetcode - 1. Two Sum

Solution that i got , not a good one but at-least mine 🙃 , the Time Complexity is O(n^2) which is not optimal .

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  let ans 

  function getAllIndexes(arr, val) {
    var indexes = [], i;
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes;
}
   nums.forEach((item,index)=>{
    const foundIndex = getAllIndexes(nums , target-item).filter((id)=> id !== index)[0];
        if(foundIndex>=0 && ans === undefined){
            ans =  [index ,foundIndex];
            return;
        }
    })
    return ans
};
Enter fullscreen mode Exit fullscreen mode

Another way of solving , using 2 pointers

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
   let left = 0;
   let right = 1
   while(left <= nums.length-1){

       if(nums[left] + nums[right] === target){
           return [left,right]
       }else if (right === nums.length-1){
           left++;
           right = left+1;
       }
       else{
           right++;
       }
   }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)