Tags

  • AWS (7)
  • Apigee (3)
  • ArchLinux (5)
  • Array (6)
  • Backtracking (6)
  • BinarySearch (6)
  • C++ (19)
  • CI&CD (3)
  • Calculus (2)
  • DesignPattern (43)
  • DisasterRecovery (1)
  • Docker (8)
  • DynamicProgramming (20)
  • FileSystem (11)
  • Frontend (2)
  • FunctionalProgramming (1)
  • GCP (1)
  • Gentoo (6)
  • Git (15)
  • Golang (1)
  • Graph (10)
  • GraphQL (1)
  • Hardware (1)
  • Hash (1)
  • Kafka (1)
  • LinkedList (13)
  • Linux (27)
  • Lodash (2)
  • MacOS (3)
  • Makefile (1)
  • Map (5)
  • MathHistory (1)
  • MySQL (21)
  • Neovim (10)
  • Network (66)
  • Nginx (6)
  • Node.js (33)
  • OpenGL (6)
  • PriorityQueue (1)
  • ProgrammingLanguage (9)
  • Python (10)
  • RealAnalysis (20)
  • Recursion (3)
  • Redis (1)
  • RegularExpression (1)
  • Ruby (19)
  • SQLite (1)
  • Sentry (3)
  • Set (4)
  • Shell (3)
  • SoftwareEngineering (12)
  • Sorting (2)
  • Stack (4)
  • String (2)
  • SystemDesign (13)
  • Terraform (2)
  • Tree (24)
  • Trie (2)
  • TwoPointers (16)
  • TypeScript (3)
  • Ubuntu (4)
  • Home

    [LeetCode 1] Two Sum

    Published Sep 29, 2021 [  Map  ]

    Problem

    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]
    Output: 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.
    

    Follow-up:

    Can you come up with an algorithm that is less than O(n2) time complexity?

    Thoughts

    Normally, array problems can be solved with the help of hash to speed up. So in this case, we can have a valueToIndex hash to store the value as we loop through the array and check for solution

    Code

    Javascript

    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    var twoSum = function(nums, target) {
        const valueToIndex = {};
    
        for(let i = 0; i < nums.length; i++){
            if (valueToIndex[target - nums[i]] !== undefined){
                return [i, valueToIndex[target - nums[i]]]
            }
            valueToIndex[nums[i]] = i;
        }
    };
    

    Typescript

    function twoSum(nums: number[], target: number): number[] {
        let valueToIndex = new Map();
        for(let index = 0; index < nums.length; index++){
            if(valueToIndex.has(target - nums[index])) {
                return [index, valueToIndex.get(target - nums[index])];
            }
            valueToIndex.set(nums[index], index);
        }
    };
    

    Ruby

    # @param {Integer[]} nums
    # @param {Integer} target
    # @return {Integer[]}
    def two_sum(nums, target)
        valueToIndex = {}
        nums.each_with_index do |value, index|
            if valueToIndex.key?(target - value)
                return [index, valueToIndex[target - value]]
            end
            valueToIndex[value] = index;
        end
    end
    

    Python

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            valueToIndex = {}
            for index, value in enumerate(nums):
                if((target - value) in valueToIndex):
                    return [index, valueToIndex[target - value]]
                valueToIndex[value] = index
    

    C++

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            map<int, int> valueToIndex;
            for(auto index = 0; index < nums.size(); index++){
                if(valueToIndex.find(target - nums[index]) != valueToIndex.end()){
                    return vector<int>{index, valueToIndex[target - nums[index]]};
                }
                valueToIndex[nums[index]] = index;
            }
            return vector<int>{};
        }
    };
    

    Go

    func twoSum(nums []int, target int) []int {
        var valueToIndex = make(map[int]int)
        for index, value := range nums {
            if secondIndex, ok := valueToIndex[target - value]; ok {
                return []int{index, secondIndex}
            }
            valueToIndex[value] = index;
        }
        return []int{}
    }
    

    Reference