diff --git a/lib/array_intersection.rb b/lib/array_intersection.rb index ac8771f..f56ec6b 100644 --- a/lib/array_intersection.rb +++ b/lib/array_intersection.rb @@ -1,3 +1,27 @@ +# Time complexity: O(n^2) +# Space complexity: O(n) + def intersection(list1, list2) - raise NotImplementedError, "Intersection not implemented" + hash = {} + list1.each do |i| + if hash[i/10] + hash[i/10] << i + else + hash[i/10] = [i] + end + end + + array = [] + list2.each do |i| + if hash[i/10] + hash[i/10].each do |x| + if i == x + array << i + break + end + end + end + end + + return array end \ No newline at end of file diff --git a/lib/palindrome_permutation.rb b/lib/palindrome_permutation.rb index f113692..3f97db8 100644 --- a/lib/palindrome_permutation.rb +++ b/lib/palindrome_permutation.rb @@ -1,4 +1,26 @@ +# Time complexity: O(n) +# Space complexity: O(n) def palindrome_permutation?(string) - raise NotImplementedError, "palindrome_permutation? not implemented" + hash = {} + + string.length.times do |i| + if hash[string[i]] + hash[string[i]] += 1 + else + hash[string[i]] = 1 + end + end + + + odd = 0 + hash.each do |k, v| + if v % 2 != 0 + if v == 1 + return false if (odd += 1) > 1 + end + end + end + + return true end \ No newline at end of file diff --git a/lib/permutations.rb b/lib/permutations.rb index 3b08381..46847ca 100644 --- a/lib/permutations.rb +++ b/lib/permutations.rb @@ -1,4 +1,24 @@ - +# Time complexity: O(n) +# Space complexity: O(n) def permutations?(string1, string2) - raise NotImplementedError, "permutations? not implemented" + return false if string1.length != string2.length + + hash = {} + string1.length.times do |i| + if hash[string1[i]] + hash[string1[i]] += 1 + else + hash[string1[i]] = 1 + end + end + + string2.length.times do |i| + if hash[string2[i]] && hash[string2[i]] > 0 + hash[string2[i]] -= 1 + else + return false + end + end + + return true end \ No newline at end of file diff --git a/test/palindrome_permutation_test.rb b/test/palindrome_permutation_test.rb index e9119de..984b333 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 79da2f6..5f6ae77 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