Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ports - Sopheary #29

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions lib/array_intersection.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
# 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.
# 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)
raise NotImplementedError
return [] if array1.nil? || array2.nil? || array1 == [] || array2 == []
return [] if array1 == [] && array2 == []
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

line 9 is repetitive - if one of array1 or array 2 == [], an empty array will be returned on line 8

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
6 changes: 3 additions & 3 deletions specs/array_intersection_spec.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down