2 Sum - Most Popular CS Interview Question and Answer: HashTable Solution in 7 Lines

preview_player
Показать описание
Most Popular Coding Interview Question: 2 Sum HashTable Solution in 7 Lines

Common computer science interview question asked by Google, Facebook, Amazon, etc..

Song: LAKEY INSPIRED - Chill Day (Vlog No Copyright Music)
Music provided by Vlog No Copyright Music.

Other Interview Questions:
Рекомендации по теме
Комментарии
Автор

Thanks DEREK. I gave it a try and this is my java implementation. Suggestions are more than welcome.

package hashtable;

import java.util.Arrays;
import java.util.Hashtable;

public class SumWithHashtable {

public static String sumTwoViaComplement(int[] array, int target) {

// Initialize components.
Hashtable<Integer, Integer> hashtable = new Hashtable<>();
int complement = 0;

// Loop array for the first two values that added equals target.
for (int i = 0; i <= array.length - 1; i++) {

// Find complement of current array value.
complement = target - array[i];

if {
// Complement found in hash table, return indexes.
return "[" + hashtable.get(complement) + ", " + i + "]";
} else {
// Complement not found, put current element into hashtable.
hashtable.put(array[i], i);
}
}
return "-1";
}

public static void main(String[] args) {

int[] array = { 2, 7, 11, 15, 6, 8, 3 };
int target = 18;

System.out.println("Given the array: " + Arrays.toString(array));
System.out.println("and target: " + target);

String indexes = sumTwoViaComplement(array, target);


? "No values added reach target"
: "First elements that added reach target are at indexes: " + indexes);
}
}

siomarapantarotto
Автор

Nice! Very clever the second solution. Where can I see the java implementation? The link to the solution is broken: That topic does not exist.

siomarapantarotto
Автор

Wow! That was a very clear explanation.
Thank you!

paulonteri
Автор

what happens if there are two possible combination? like if target was 15 and we had
[2, 5, 10, 13]

ILagable
Автор

What if for cases that an element appears twice in the array.

peculiarpeculiar