From 512146969e0e42be0ea0b7941e0ed29d94e62d24 Mon Sep 17 00:00:00 2001 From: Sophearychiv Date: Tue, 30 Apr 2019 08:17:48 -0700 Subject: [PATCH 1/2] passed tests --- lib/array_intersection.rb | 20 +++++++++++++++++--- specs/array_intersection_spec.rb | 6 +++--- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index 478b24e..fc2a228 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -1,6 +1,20 @@ # Returns a new array to that contains elements in the intersection of the two input arrays -# Time complexity: ? -# Space complexity: ? +# Time complexity: O(n x m) where n is the length of array1, and m is the length +# of array2 since the method loops through both arrays. +# Space complexity: O(n) because the intersection array stores the output. def intersection(array1, array2) - raise NotImplementedError + return [] if array1.nil? || array2.nil? || array1 == [] || array2 == [] + return [] if array1 == [] && array2 == [] + return array1 if array1 == array2 + + intersection = [] + array1.each do |i| + array2.each do |j| + intersection << i if i == j + end + end + + return intersection end + +p diff --git a/specs/array_intersection_spec.rb b/specs/array_intersection_spec.rb index b35e56e..5f19019 100644 --- a/specs/array_intersection_spec.rb +++ b/specs/array_intersection_spec.rb @@ -1,6 +1,6 @@ -require 'minitest/autorun' -require 'minitest/reporters' -require_relative '../lib/array_intersection' +require "minitest/autorun" +require "minitest/reporters" +require_relative "../lib/array_intersection" describe "array intersection" do describe "basic tests" do From e903c3b4b4057ab91e87fb98eb22ec8bc80e933c Mon Sep 17 00:00:00 2001 From: Sophearychiv Date: Tue, 30 Apr 2019 08:20:56 -0700 Subject: [PATCH 2/2] added more answers --- lib/array_intersection.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index fc2a228..b55e73a 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -2,6 +2,8 @@ # Time complexity: O(n x m) where n is the length of array1, and m is the length # of array2 since the method loops through both arrays. # Space complexity: O(n) because the intersection array stores the output. +# Other strategies: I was trying to apply binary search to replace the second inner loop +# but could not get it work because of infinite looping. def intersection(array1, array2) return [] if array1.nil? || array2.nil? || array1 == [] || array2 == [] return [] if array1 == [] && array2 == []