Facebook Interview Question
Software Engineer / DevelopersTeam: Facebook groups
Country: United States
public static boolean findIfAnyTripletsOfArraySumsToResult(int[] a, int result) {
int k=0,due =0;
Set complimentsWhenKey = new HashSet();
while(k<a.length){
complimentsWhenKey.clear();
due=result-a[k];
for(int i=0;i<a.length;i++ ) {
if(i==k ){
i=i+1;
}
if(i<=a.length-1) {
if(complimentsWhenKey.contains(a[i])){
return true;
}
complimentsWhenKey.add(due - a[i]);
}
}
k++;
}
return false;
}
It's great to use a hash table and store partial results.
jayakrishnan.somasekharannair solution is nice! But it doesn't need to do:
for(int i=0;i<a.length;i++ )
as every time I only need to check the elements at the right of k, no need to restart from zero. I would say:
for(int i=k;i<a.length;i++ )
That's my solution in swift
func constantIsSumOf3Elements(_ array:[Int], c:Int) -> Bool {
var hash = Set<Int>()
for (i, element) in array.enumerated() {
hash.removeAll()
let due = c-element
for j in (i+1)..<array.count {
if hash.contains(array[j]) {
print("\(element) + \(due-array[j]) + \(array[j]) = \(c)")
return true
}
hash.insert(due-array[j])
}
}
return false
}
let _ = constantIsSumOf3Elements([6,5,3,2,1,1,21], c:28)
//Output: 6 + 1 + 21 = 28
void findTriplets2(int[] a, int sum) {
HashMap<Integer, Integer> hm = new HashMap<>();
for (int i = 0; i < a.length; i++) {
hm.put(a[i], a[i]);
}
if (a.length == 3 && a[0] + a[1] + a[2] == sum) {
System.out.println(a[0] + " + " + a[1] + " + " + a[2]);
return;
}
for (int i = 0; i < a.length - 2; i++){
for (int j = i + 1; j < a.length; j++){
int diff = sum - (a[i] + a[j]);
if (hm.get(diff) != null) System.out.println(+ a[i] + " + " + a[j] + " + " + diff);
}
}
}
}
Java
Time: O(n^2)
Space: O(n)
- jason April 11, 2018