diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index ac8771f..04cef67 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -1,3 +1,17 @@ +# Takes two integer arrays as arguments and returns a new array of their intersecting numbers. +#Time complexity: O(n), worse case scenario we iterate over every item in both lists +#Space complexity: O(n), creating a new hash and a new array def intersection(list1, list2) - raise NotImplementedError, "Intersection not implemented" + integer_hash = {} + + list1.each do |int| + integer_hash[int] = 1 + end + + intersection = [] + list2.each do |int| + intersection << int if integer_hash.has_key?(int) + end + + return intersection end \ No newline at end of file diff --git a/lib/palindrome_permutation.rb b/lib/palindrome_permutation.rb index f113692..ce9524a 100644 --- a/lib/palindrome_permutation.rb +++ b/lib/palindrome_permutation.rb @@ -1,4 +1,21 @@ +# Takes a string as an argument and checks if it could be a valid palindrome. +# Valid palindromes have a maximum of one letter that appears an odd number of times. +# Time: O(n), we iterate over the string once and over our hash once +# Space: O(n), worse case scenario we create a new hash collection that's as "large" as our string def palindrome_permutation?(string) - raise NotImplementedError, "palindrome_permutation? not implemented" + hash = {} + + string.chars.each do |letter| + hash.has_key?(letter) ? hash[letter] += 1 : hash[letter] = 1 + end + + pivot_letters = 0 + + hash.each do |k, v| + pivot_letters += 1 if v.odd? + return false if pivot_letters > 1 #catch early cases of finding more than 1 pivot letter + end + + return true end \ No newline at end of file diff --git a/lib/permutations.rb b/lib/permutations.rb index 3b08381..97e554d 100644 --- a/lib/permutations.rb +++ b/lib/permutations.rb @@ -1,4 +1,20 @@ +# Accepts two strings as arguments and checks if they're permutations of each other. +# Permutations share the same letter counts between each other. +# Time: O(n), we iterate through three different collections of fixed size +# Space: O(n), we create a new hash + def permutations?(string1, string2) - raise NotImplementedError, "permutations? not implemented" + hash = {} + + string1.chars.each do |letter| + hash.has_key?(letter) ? hash[letter] += 1 : hash[letter] = 1 + end + + string2.chars.each do |letter| + return false unless hash.has_key?(letter) && hash[letter] > 0 #quickly catch obvious fail cases + hash[letter] -= 1 + end + + return !(hash.any? {|key, value| value > 0}) end \ No newline at end of file