LeetCode 1. Two Sum (javascript solution)
codingpineapple
Posted on April 17, 2021
Description:
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.
Solution:
Time Complexity : O(n)
Space Complexity: O(n)
var twoSum = function(nums, target) {
const store = {}
for(let i = 0; i < nums.length; i++){
let cur = nums[i]
let diff = target - cur
// Return answer if the current number was a diff from a previous number
if(store[cur]!==undefined) return [store[cur], i]
// Set diff to current index in store
else store[diff] = i
}
};
π πͺ π
π©
codingpineapple
Posted on April 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
sorting Recap the highlight of the sorting algorithms using JavaScript for beginners
October 5, 2024
datastructures DSA with JS: Understanding Custom Array Data Structure in JavaScript - A Step-by-Step Guide
September 29, 2024