Skip to content

Conversation

@shirley1chu
Copy link

No description provided.

# Returns a new array to that contains elements in the intersection of the two input arrays
# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n), because the lookup for a hash is constant, and the times we do a lookup depends on the length of the longer array

Choose a reason for hiding this comment

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

I believe this is an implementation of insertion sort, which is quadratic in time complexity.
Source 1: Comparison Sort
Source 2: Time Complexity

# Time complexity: ?
# Space complexity: ?
# Time complexity: O(n), because the lookup for a hash is constant, and the times we do a lookup depends on the length of the longer array
# Space complexity: O(n). where n is the length of the shortest array, since all elements of the shortest array are plaeced in the hash

Choose a reason for hiding this comment

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

If it is quadratic, space complexity is O(1).


intersection_array = []
longer_array.each do |element|
intersection_array.push(element) if shorter_array_hash.include?(element)

Choose a reason for hiding this comment

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

Nice use of include?

shorter_array_hash = {}

until index > shorter_array.length
shorter_array_hash[shorter_array[index]] = 1

Choose a reason for hiding this comment

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

I am not sure if you need a hash here. If the intersection of the arrays had multiple values that were in common (example:

test1 = [1,2,3,4,5,5,5]
test2 = [5,5,5,5,5]

shorter_array_hash would be reset to a value of 1 each time for every iteration of 5. I think an array would work for your purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants