From ba3ce32b0b4cadee4235a5c104b1eddadc50b04f Mon Sep 17 00:00:00 2001 From: Kelly Downes Date: Sat, 14 Sep 2019 16:42:33 -0700 Subject: [PATCH] Complete anagram problem --- lib/exercises.rb | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 2cb2bfa..996af83 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -2,11 +2,17 @@ # 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) +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + grouped = Hash.new([]) + + strings.each.with_index do |word, i| + grouped[word.chars.sort.join] += [i] + end + + return grouped.map { |key, indices| indices.map { |i| strings[i] } } end # This method will return the k most common elements @@ -17,14 +23,13 @@ def top_k_frequent_elements(list, k) raise NotImplementedError, "Method hasn't been implemented yet!" end - # This method will return the true if the table is still # a valid sudoku table. # Each element can either be a ".", or a digit 1-9 -# The same digit cannot appear twice or more in the same +# The same digit cannot appear twice or more in the same # row, column or 3x3 subgrid # Time Complexity: ? # Space Complexity: ? def valid_sudoku(table) raise NotImplementedError, "Method hasn't been implemented yet!" -end \ No newline at end of file +end