Leetcode problem- TwoSum

Visakh Vijayan
1 min readApr 14, 2025

--

I like to solve some leetcode problems and see how much faster they can be made. Today, we are solving the TwoSum problem. Below are two of the solutions.

Problem: https://leetcode.com/problems/two-sum/description/

Solution 1 — Runs in 35 ms — O(n²) time complexity

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let map = {};

for (let i = 0; i < nums.length; i++) {
let needed = target - nums[i];

if (map[needed] !== undefined) {
return [map[needed], i];
} else {
map[nums[i]] = i;
}
}

return [];
};

Solution 2 — Runs in 1 ms — O(n) time complexity

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let map = {};

for (let i = 0; i < nums.length; i++) {
let needed = target - nums[i];

if (map[needed] !== undefined) {
return [map[needed], i];
} else {
map[nums[i]] = i;
}
}

return [];
};

It feels so good when your solution becomes faster!!!

And the happiness feeling. Little drops of joy!

--

--

Visakh Vijayan
Visakh Vijayan

Written by Visakh Vijayan

Techie from Kerala, India. Days are for coding, nights for weaving tales of tech, travel, and finance. Join me in exploring this multifaceted journey

No responses yet