DEV Community

Cover image for Two Sum - LeetCode
zuzexx
zuzexx

Posted on

Two Sum - LeetCode

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.

In this challenge, you are given an array of integers nums and an integer target, and your goal is to return the indices of the two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

The solution to this problem can be achieved through a nested loop. The outer loop starts from the first element in the array, and the inner loop starts from the next element after the current outer loop element. The inner loop checks if the sum of the current outer loop element and the current inner loop element is equal to the target. If it is, we return an array of the indices of the two elements, which represent the solution to the challenge.

Here is the code for the solution:

var twoSum = function(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) {
        let result = [i, j];
        return result;
      }
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

Let's walk through an example to understand how the code works. Let's say the array nums is [2, 7, 11, 15]
and the target is 9.

  1. The outer loop starts with the first element in the array, which is 2, and the inner loop starts from the next element, which is 7.

  2. The inner loop checks if 2 + 7 = 9, which is true, and returns the indices of the two elements, which are [0, 1].

As you can see, the solution to the two sum challenge can be easily achieved through a nested loop in JavaScript. The time complexity of this solution is O(n^2) because it has two nested loops, but it still works well for small arrays.

Top comments (0)