diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index ac8771f..1e0ad4d 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -1,3 +1,17 @@ +# time complexity: O(n + m) +# space complexity: O(n) + def intersection(list1, list2) - raise NotImplementedError, "Intersection not implemented" + hash_table = {} + intersection_array = [] + + list1.each do |num| + hash_table[num] = 1 + end + + list2.each do |num| + intersection_array << num if hash_table[num] + end + + return intersection_array end \ No newline at end of file diff --git a/lib/palindrome_permutation.rb b/lib/palindrome_permutation.rb index f113692..a384873 100644 --- a/lib/palindrome_permutation.rb +++ b/lib/palindrome_permutation.rb @@ -1,4 +1,19 @@ - +# time complexity: O(n) +# space complexity: O(n) def palindrome_permutation?(string) - raise NotImplementedError, "palindrome_permutation? not implemented" + return true if string.length == 1 || string.length == 0 + + split_string = string.chars + hash_table = {} + + split_string.each do |char| + value = hash_table[char] + hash_table[char]? hash_table[char] = value +1 : hash_table[char] = 1 + end + + odd_count = 0 + hash_table.values.each do |value| + odd_count += 1 if value.odd? + end + odd_count <= 1 ? true : false end \ No newline at end of file diff --git a/lib/permutations.rb b/lib/permutations.rb index 3b08381..5dd0902 100644 --- a/lib/permutations.rb +++ b/lib/permutations.rb @@ -1,4 +1,24 @@ +# time complexity: O(n + m) +# space complexity: O(n) def permutations?(string1, string2) - raise NotImplementedError, "permutations? not implemented" + return true if string1.empty? && string2.empty? + + split_string1 = string1.chars + split_string2 = string2.chars + + hash_table = {} + + split_string1.each do |char| + value = hash_table[char] + hash_table[char] ? hash_table[char] = value + 1 : hash_table[char] = 1 + end + + split_string2.each do |char| + value = hash_table[char] + hash_table[char] ? hash_table[char] = value - 1 : false + end + + return hash_table.values.sum == 0 && hash_table.values.min == 0 ? true : false + end \ No newline at end of file diff --git a/test/palindrome_permutation_test.rb b/test/palindrome_permutation_test.rb index 6e43777..246ccfd 100644 --- a/test/palindrome_permutation_test.rb +++ b/test/palindrome_permutation_test.rb @@ -1,6 +1,6 @@ require_relative "test_helper" -xdescribe "palindrome_permutation?" do +describe "palindrome_permutation?" do it "will work for hello" do expect(palindrome_permutation?("hello")).must_equal false end diff --git a/test/permutations_test.rb b/test/permutations_test.rb index eb1ce8c..792d9ef 100644 --- a/test/permutations_test.rb +++ b/test/permutations_test.rb @@ -1,6 +1,6 @@ require_relative "test_helper" -xdescribe "permutations?" do +describe "permutations?" do it "returns true for empty string" do expect(permutations?("", "")).must_equal true end