Skip to content
Open
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+m) ~= O(n) where n is the length of the larger array because the code iterates through each item in both of the arrays. Looking up items in a hash table is O(1) time complexity; therefore the linear time complexity is dependent on the size of the larger array.
# Space complexity: O(n) - a new array is created to store intersecting values so space complexity is (worst-case) dependent on the length, n, of the array
Copy link
Copy Markdown

@eric-andeen eric-andeen Apr 19, 2019

Choose a reason for hiding this comment

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

Space complexity is O(n) for your solution - you're essentially making a whole copy of array1 in the hash. The assignment specifically says you should minimize space complexity. Can you do better than O(n)? Hint - the answer is yes.

def intersection(array1, array2)
raise NotImplementedError
if array1.nil? || array2.nil? || array1 == [] || array2 == []
return []
end

new_hash = Hash.new
common_values = []
array1.each do |num|
new_hash[num] = 1
end

array2.each do |num|
if new_hash.include?(num)
common_values << num
end
end

return common_values
end