Approaching Algorithms with JavaScript

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Problem Solving Approach

for example:nums = [2,7,11,15], target = 92+7=9 -- return these indices!
2+11!=9
2+15!=9
7+11!=9
7+15!=9
11+15!=9
return [0, 1]
// Define a function with 2 arguments (nums and target)// For the currentIndice in the array, check against the sum of the currentIndice and the nextIndice against the target.// If sum of currentIndice and nextIndice === target, return the indices of currentIndice and nextIndice.// Iterate through each element of the array.
const twoSum = (nums, target) => {
let indices = [];
for(let i = 0; i < nums.length; i++){
for(let j = i + 1; j < nums.length; J++}{
if(nums[i] + nums[j] === target}{
indices.push(i);
indices.push(j);
}
}
}
return indices;
}
const twoSum = (nums, target) {
for (let i = 0; j = nums.length - 1; i < j;) {
let sum = nums[i] + nums[j];
if (sum === target) {
return new Array(i + 1, j + 1);
} else if (sum < target) {
i++;
} else {
j--;
}
}
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store