From 85c6865ae5f5f918a8004f20af9086549b47ac96 Mon Sep 17 00:00:00 2001 From: Jocelyn Wang Date: Thu, 15 Oct 2020 13:08:05 -0700 Subject: [PATCH 1/2] grouped anagrams --- lib/exercises.rb | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..d45aa96 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,11 +1,45 @@ # This method will return an array of arrays. # Each subarray will have strings which are anagrams of each other -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n * m) +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + words = {} + + while !strings.empty? + i, word_to_compare = 0, strings[0] + words[word_to_compare] = [] + + while i < strings.length + if permutation(word_to_compare, strings[i]) + words[word_to_compare].push(strings[i]) + strings.delete_at(i) + i -= 1 + end + i += 1 + end + end + + return words.values +end + +def permutation(str1, str2) + return true if str1.empty? && str2.empty? + return false if str1.nil? || str2.nil? + return false if str1.empty? || str2.empty? + + hash = {} + + str1.each_char do |char| + hash[char] ? hash[char] += 1 : hash[char] = 1 + end + + str2.each_char do |char| + hash[char] ? hash[char] -= 1 : false + end + + return hash.values.all? { |value| value == 0 } end # This method will return the k most common elements From 28e49af5ed5ff4cd3719ced557edf961198ae528 Mon Sep 17 00:00:00 2001 From: Jocelyn Wang Date: Thu, 15 Oct 2020 13:25:33 -0700 Subject: [PATCH 2/2] top k frequent --- lib/exercises.rb | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index d45aa96..7da0b9c 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -47,7 +47,29 @@ def permutation(str1, str2) # Time Complexity: ? # Space Complexity: ? def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if list.empty? || k == 0 + + hash, result = [], [] + + list.each do |num| + hash[num] ? hash[num] += 1 : hash[num] = 1 + end + + k.times do |time| + max_count, top_occurence = 0, nil + + list.each do |num| + if hash[num] > max_count + max_count = hash[num] + top_occurence = num + end + end + + result << top_occurence + list -= [top_occurence] + end + + return result end