top of page

1. Two Sum

Overall

Difficulty: Easy   

Link: https://leetcode.com/problems/two-sum/

Introduction

Two Sum is a first problem in Leetcode. It is a start point of Leetcode journey. If you can success to solve it. You can start your Leetcode journey.

​

If you can complete this problem, you will have accomplished the first task. It will give you a small sense of pride, and it will encourage you to do another task and another and another.

​

If you can't do the little things right, you'll never be able to do the big things right.

Problem Content

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.


Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6 Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6 Output: [0,1]


Constraints:

  • 2 <= nums.length <= 104

  • -109 <= nums[i] <= 109

  • -109 <= target <= 109

  • Only one valid answer exists.

Concept

The problem is provide an array called "nums" then the program need to return which two number can make the sum is meet the target.

​

First, we use for loop(for (let i = 0; i < nums.length; i++)) to check the first number. Next we include another for loop(for (let j = i+1; j < nums.length; j++)) in above for loop to check second number, because the return array must not include two numbers at same place in array and we need to avoid the program check the same combination again, we use "let j = i+1" that can make the program use fewer time to check different combination.

​

If nums[i] and nums[j] can make the sum is meet the target, the program return the array include nums[i] and nums[j]. If all combination cannot meet the target after finish all for loop in program, the program should return null.

Solve(Javascript)

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){
                return [i,j]
            }
        }
    }
    return null;
};

bottom of page