From 2c1ef49d93f775d69a884892cefe87fc88ed91c4 Mon Sep 17 00:00:00 2001 From: Pauline Sauget Date: Sun, 5 May 2019 20:16:08 -0700 Subject: [PATCH] Solve with hash function approach --- lib/array_intersection.rb | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index 478b24e..57d7291 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -1,6 +1,24 @@ # Returns a new array to that contains elements in the intersection of the two input arrays -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n) to hash in, O(m) to look up, where n is length of array1 and m is length of array 2 +# Space complexity: O(n) to add to hash table, O(n) for results array def intersection(array1, array2) - raise NotImplementedError + intersection = [] + return intersection if !array1 || !array2 + if array1.length < array2.length + smaller = array1 + larger = array2 + else + smaller = array2 + larger = array1 + end + + my_hash = {} + smaller.each do |num| + my_hash[num] = 1 + end + + larger.each do |num| + intersection << num if my_hash.include?(num) + end + return intersection end