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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay