Here is the interview question prompt, presented for reference.
This is a classic and very common interview problem. Given an array of integers, return the indices of the two numbers in it that add up to a specific "goal" number.
Suppose we had an array [1, 3, 6, 7, 9]
, and let's say our "goal" number was 10
. Our numbers to sum to it could be 3
and 7
, and we would return an array of indices 1
and 3
respectively.
let arr = [1, 3, 6, 7, 9];
let goal = 10;
twoSum(arr, goal);
// [1, 3]
arr = [1, 3, 6, 7, 9]
goal = 10
two_sum(arr, goal)
# [1, 3]
You may assume that each input would have exactly one solution. Additionally, you may not use the same element twice towards the sum. This means if given [1, 3]
and a goal of 2
, you cannot use 1
twice and return its index twice as [0, 0]
.
Note that you cannot guarantee the array is sorted.
AlgoDaily partner CodeTips.co.uk has kindly provided a guide on solving Two Sum in Go. Check it out for even deeper coverage of this problem.
100000
-1000000000
and 1000000000
-1000000000
and 1000000000
O(n)
O(n)
You can see the full challenge with visuals at this link.
Challenges • Asked over 5 years ago by Noobert
This is the main discussion thread generated for Two Sum.
function twoSum(arr, goal) {
let results = [];
for (let i = 0; i < arr.length; i++){
if (arr.indexOf(goal - arr[i]) > 0){
results.push(i, arr.indexOf(goal - arr[i]));
break;
}
}
return results;
}
private static int[] getIndices(int[] a, int k) {
HashMap
for(int i=0;i
The following solution shows being faster than the provided solution on jsbench.me:
function twoSum(arr, goal) {
const results = [];
const hashmap = {};
for (let i = 0; i < arr.length; i++) {
hashmap[arr[i]] = i;
const mate = goal - arr[i];
if (hashmap[mate] != null) {
results.push(hashmap[mate]);
results.push(i);
break;
}
}
return results;
}
Is there a difference in using the Two Pointer approach versus a Hash Map for this problem? I was initially using the Two Pointer approach to solve this. I believe there time complexities are both O(n). Just not too sure which approach would be best in an interview setting.
Hi Tim,
Both approaches work well! The hash map takes O(n)
more space (since it needs to store each input element in the array as keys), so complexity-wise Two Pointers are better (O(1)
space).
The below solution seems to work fine. But when I submit the tests are being called for sortedtwosum.
public static int[] twoSum(int[] arr, int goal){
int[] result = new int[2];
HashMap resultMap = new HashMap();
for(int i=0;i
Thank you, Anil! This is resolved.