Pinterest Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
this is similar to the box problem, which asks for putting bigger box under smaller boxes and returning the max height from a list of boxes
use one integer as bit vector to represent the current word
pseudo code:
int maxlength(int bitvector){
max=0;
for(word: list){
if(word contains the previous bit vector){
update the bit vector
if(maxlength(bitvector)>max) update max;}
}
besides use memorizing to reduce duplicates
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
def hash_anagram(s):
hash = 1
for c in s.lower():
hash *= primes[ord(c) - ord('a')]
return hash
def longest_anagram_derivative(words):
hashedWords = [(hash_anagram(w), w) for w in words]
hashedWords.sort(reverse=True)
for i, (hashCode, word) in enumerate(hashedWords):
for j in range(i + 1, len(hashedWords)):
if hashCode % hashedWords[j][0] == 0:
return word
return None
print longest_anagram_derivative(['a', 'cat', 'tack', 'tacky', 'bla', 'able', 'whatever']) # prints: whatever
print longest_anagram_derivative(['b', 'cat', 'tack', 'tacky', 'bla', 'able', 'whatever']) # prints: tacky
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
def hash_anagram(s):
hash = 1
for c in s.lower():
hash *= primes[ord(c) - ord('a')]
return hash
def longest_anagram_derivative(words):
hashedWords = [(hash_anagram(w), w) for w in words]
hashedWords.sort(reverse=True)
for i, (hashCode, word) in enumerate(hashedWords):
for j in range(i + 1, len(hashedWords)):
if hashCode % hashedWords[j][0] == 0:
return word
return None
print longest_anagram_derivative(['a', 'cat', 'tack', 'tacky', 'bla', 'able', 'whatever']) # prints: whatever
print longest_anagram_derivative(['b', 'cat', 'tack', 'tacky', 'bla', 'able', 'whatever']) # prints: tacky
-EDIT-
- Cerberuz February 12, 2013This won't work. Will try another approach.