Pergunta de entrevista da empresa Meta

The first Jedi question was this: given an unsorted array of numbers, like [1, 3, 5, 4, 2], write a function that takes an integer and returns true if there's any pair of numbers in that array that can be summed up to the input integer.

Respostas da entrevista

Sigiloso

19 de out. de 2017

Given that this was an iOS interview, I solved this using Objective-C: NSArray *inputArray = @[@1, @3, @5, @4, @2]; - (BOOL) pairOfNumberIn: (NSArray *) inputArray matches: (int) sumNumber { NSMutableDictionary *destinationDict; for eachInput in inputArray { // we know what number we need to sum up to the "seekNumber" seekValue = sumNumber - eachInput.intValue; // if it exists in the destinationDict-ionary, then we can return YES if [destinationDict objectForKey: value] return TRUE; else { // otherwise add this seekValue to the destinationDict [destinationDict setObject: eachInput forKey: [NSNumber numberWithInt: seekValue]]; } } return FALSE; } If we look for 7, the inputArray values of 1, 3 & 5 correspond to 6, 4, & 2. When we hit 4 in the inputArray, we've already calculated that we need a 4 to hit the sumNumber so an object for that key exists and we can return TRUE. I probably could have simplified this down to a NSMutableArray with corresponding seekValues.

1

Sigiloso

1 de fev. de 2018

func twoSum(array:[Int], n:Int)->Bool{ var memo = [Int:Bool]() for v in array{ if memo[n-v] ?? false {return true} memo[v] = true } return false }

Sigiloso

11 de jun. de 2018

Answer is very simple O(n) at worst. 1. Create a set from input array 2. loop through input array and find difference between target number and current number 3. Check that the set contains that difference. If it does -> return true func findSummation(from input: [Int], number: Int) -> Bool { let aset = Set(input) for item in input { let diff = number - item if aset.contains(diff) { return true } } return false }

Sigiloso

4 de fev. de 2018

#import @interface ArrayUtility: NSObject @end @implementation ArrayUtility + (BOOL)pairOfNumbersIn:(NSArray *)array matches:(NSInteger)sum { NSMutableSet *set = [NSMutableSet set]; for (NSNumber *number in array) { if ([set containsObject:@(sum - number.intValue)]) { return true; } [set addObject:number]; } return false; } @end int main(int argc, const char * argv[]) { @autoreleasepool { NSArray *array = @[ @1, @2, @3, @4, @5]; BOOL mathes = [ArrayUtility pairOfNumbersIn:array matches:7]; if (mathes) { NSLog(@"Found"); } else { NSLog(@"Could not find"); } } return 0; }