Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save codertcet111/cf70b32368c0eebd1678c34f8b571377 to your computer and use it in GitHub Desktop.
Save codertcet111/cf70b32368c0eebd1678c34f8b571377 to your computer and use it in GitHub Desktop.
49. Leetcode group anagrams problem with 3 approaches
=begin
Leetcode 49. Group Anagrams
Given an array of strings strs, group the
anagrams
together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
There is no string in strs that can be rearranged to form "bat".
The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
=end
# @param {String[]} strs
# @return {String[][]}
## Approach with 2D matrix with 26 alphabet approach
def group_anagrams(strs)
ascii_str_a = 97
mtrx = Array.new(strs.length) { Array.new(26) {0}}
strs.each_with_index do |st, i|
st.split('').each do |ch|
j = ch.ord - ascii_str_a
mtrx[i][j] += 1
end
end
# Initialize a hash to group anagrams
anagram_groups = Hash.new { |hash, key| hash[key] = [] }
# Go through the matrix and group the rows that are identical
mtrx.each_with_index do |row, i|
anagram_groups[row] << i
end
anagram_groups.values.map{|x| temp_a = []; x.each{|i| temp_a << strs[i]}; temp_a }
end
def group_anagrams(strs)
sum_ascii_hash = {}
strs.each_with_index do |str, i|
sorted_aa = str.chars.sort.join
sum_ascii_hash["#{sorted_aa}"] ? sum_ascii_hash["#{sorted_aa}"] << i : sum_ascii_hash["#{sorted_aa}"] = [i]
end
sum_ascii_hash.values.map{|ind_arr| ind_arr.map{|ind| strs[ind]}}
end
# Partially correct approach by calculating ascii value
def old_group_anagrams(strs)
sum_ascii_hash = {}
strs.each_with_index do |str, i|
sum_key = str.split("").uniq.sum { |char| char.ord }
Ignore: #sum_key = str.split("").sum { |char| char.ord }
Ignore: #sum_key = str.split("").each_with_index.map{|char, i| char.ord * i}.sum
sum_ascii_hash["#{sum_key}"] ? sum_ascii_hash["#{sum_key}"] << i : sum_ascii_hash["#{sum_key}"] = [i]
end
sum_ascii_hash.values.map{|ind_arr| ind_arr.map{|ind| strs[ind]}}
end
@codertcet111
Copy link
Author

Screenshot 2024-10-23 at 9 46 01 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment