Pergunta de entrevista da empresa Yelp

The technical question was: You're given an array of strings. Sort it so that the result returns an array of an array of strings sorted into its anagrams. (e.g. input: ["aa", "ad", "da"], output: [ ["aa"], ["ad", "da"] ]

Respostas da entrevista

Sigiloso

8 de mar. de 2015

from collections import defaultdict def isAnagram(word, otherWord): if len(word) != len(otherWord): return False word_dict = defaultdict(int) otherWord_dict = defaultdict(int) for char in word: word_dict[char] += 1 for char in otherWord: otherWord_dict[char] += 1 for char, count in word_dict.items(): if count != otherWord_dict[char]: return False return True def main(): lst = None with open('data.txt', 'r') as f: lst = f.readline().split() i = 0 ans = [] visited = set() for word in lst[i:]: if word not in visited: temp = [word] for otherWord in lst[i+1:]: if word != otherWord and otherWord not in visited and isAnagram(word, otherWord): temp.append(otherWord) visited.add(otherWord) visited.add(word) ans.append(temp) print ans if __name__ == '__main__': main()

Sigiloso

24 de mar. de 2015

in ruby def print_anagrams_group(arr) arr.group_by { |element| element.downcase.chars.sort }.values end print_anagrams_group(["aa", "ad", "da"]) #=> [["aa"], ["ad", "da"]]

Sigiloso

1 de fev. de 2014

def yp(words): words = set(words) # to make searh O(1) out = [] while words: # cost O(N * O(1)) := O(N) word = words.pop() anagram = reversed(word) if anagram in words: words.discard(anagram) out.append([word, anagram]) else: out.append([word]) return sorted(out) # O(C * N * log(N)) + O(N) := O(N * log(N)) if __name__ == "__main__": print( yp(["aa", "ad", "da"]) )

1