Advanced · Techniques · 209 of 264
Anagram groups
Group the words that are anagrams of each other. Inside a group, sort the words alphabetically; print the groups sorted by their first word.
Input: one line of words in small letters. Output: one group per line.
Examples
Input
eat tea tan ate nat bat
Output
ate eat tea bat nat tan
Input
abc
Output
abc
One more test checks other inputs when you press Check.
Stuck? The idea behind techniques
Some problems have a known shape. Two pointers move from both ends of a sorted list. A sliding window keeps a running total as it moves, adding one item and taking one away.
A dictionary of what has been seen turns a search inside a loop into a single lookup.
nums = [2, 7, 11, 15]
target = 9
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
print(seen[target - x], i)
seen[x] = iWatch for: A loop inside a loop over the same long list is slow: the hidden tests may use big inputs.