Group Anagrams
LeetCode 49 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Key = sorted word (or letter-count tuple); group by key.
ನಾನು Group Anagrams (LeetCode 49) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Hashing / Anagram ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Anagrams share a signature — the same multiset of letters. Use that signature as a dictionary key and every word lands in its group automatically. The signature can be the sorted string or a 26-count tuple.
Approach
- 1
For each word, compute its signature.
- 2
Sorted letters: 'eat' → 'aet'.
- 3
Count tuple: 26 counts, avoids sorting each word.
- 4
Append the word to mpp[signature]; return the groups.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ
Group by ''.join(sorted(word)).
Group by a 26-length frequency tuple.
Sorted-string keyPythonO(n·k log k) time
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
mpp = defaultdict(list)
for cur_string in strs:
sorted_string= "".join(sorted(cur_string))
mpp[sorted_string].append(cur_string)
res =[]
for key,val in mpp.items():
res.append(val)
return res
"""
maintain a freq arr of size 26 for each string
abbcccc
{(1,2,4,0.....)}
bbacccc
{(1,2,4,0.....)}
"""Count-tuple keyPythonO(n·k) time
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
mpp = defaultdict(list)
res=[]
for cur_string in strs:
freq_arr = [0]*26
for char in cur_string:
freq_arr[ord(char)-ord('a')]+=1
mpp[tuple(freq_arr)].append(cur_string)
for key,val in mpp.items():
res.append(val)
return resGroup Anagrams — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Group Anagrams ಹಿಂದಿನ intuition ಏನು?
Anagrams share a signature — the same multiset of letters. Use that signature as a dictionary key and every word lands in its group automatically. The signature can be the sorted string or a 26-count tuple.
Group Anagrams (LeetCode 49) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. For each word, compute its signature. 2. Sorted letters: 'eat' → 'aet'. 3. Count tuple: 26 counts, avoids sorting each word. 4. Append the word to mpp[signature]; return the groups.
Group Anagrams ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n · k) with counts (O(n · k log k) with sorting). Space: O(n · k). (Accepted approach: Count-tuple key.)
Group Anagrams ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Lists aren't hashable — convert the count array to a tuple.
Group Anagrams ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?
Sorted-string key (O(n·k log k) time): Group by ''.join(sorted(word)). Count-tuple key (O(n·k) time): Group by a 26-length frequency tuple.