From f4954638c842826b790b9ea2d7b286a7584e2fce Mon Sep 17 00:00:00 2001 From: Tatiana Quintana Date: Tue, 16 Apr 2019 08:54:13 -0700 Subject: [PATCH 1/3] used sort to solve this problem. --- lib/array_intersection.rb | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index 478b24e..ebb546c 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -1,6 +1,27 @@ # Returns a new array to that contains elements in the intersection of the two input arrays -# Time complexity: ? -# Space complexity: ? +# Time complexity: n*m +# Space complexity: Can be On (sorting in place possible) def intersection(array1, array2) - raise NotImplementedError + unless array1 && array2 + return [] + end + + if array1.length < array2.length + smaller = array1.sort + larger = array2.sort + else + smaller = array2.sort + larger = array1.sort + end + + i = 0 + result = [] + smaller.each do |num| + larger.each do |other| + if num == other + result << num + end + end + end + return result end From 20d089027a93971cc6e7f09ae62a5ef706a6e5b6 Mon Sep 17 00:00:00 2001 From: Tatiana Quintana Date: Tue, 16 Apr 2019 08:54:43 -0700 Subject: [PATCH 2/3] removed the unnecessary sort to make less expensive --- lib/array_intersection.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index ebb546c..ef05334 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -7,10 +7,10 @@ def intersection(array1, array2) end if array1.length < array2.length - smaller = array1.sort + smaller = array1 larger = array2.sort else - smaller = array2.sort + smaller = array2 larger = array1.sort end From 8b976ae7cf4c3792f958aa562ab033a83273c0bd Mon Sep 17 00:00:00 2001 From: Tatiana Quintana Date: Sun, 21 Apr 2019 21:56:49 -0700 Subject: [PATCH 3/3] wrote more descriptive time/space complexity responses --- lib/array_intersection.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index ef05334..dc6f018 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -1,6 +1,6 @@ # Returns a new array to that contains elements in the intersection of the two input arrays -# Time complexity: n*m -# Space complexity: Can be On (sorting in place possible) +# Time complexity: n*m or quadratic time complexity that is dependent on length of smaller array +# Space complexity: Up to On after sorting (in place is possible) where n is length of smaller array def intersection(array1, array2) unless array1 && array2 return []