Member-only story

Coding Interview Prep: Two Sum Question — 2 Solutions in JavaScript

Marika Lam
2 min readJul 1, 2024

--

Prompt

Solution 1: Brute Force Method

Complexity: O(n²)

  • U
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/

//O(n^2) brute force method
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 new Array(i, j);
}
}
}
return [];
};

Solution 2: Hash Map

Complexity: O(n)

  • Use a memory to keep data for something to improve time complexity. Here we will use a Hash Map.
  • ‘n’ is the number of elements in input array. In the worst case, we put all numbers in map.
  • A map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values like string, number and boolean ) may be used as either a key or a value.
  • A key in the Map may only occur once. It is unique in the Map’s collection.
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target){…

--

--

No responses yet