Google
4.2 of 5 2,091 reviews
www.google.com Mountain View, CA 5000+ Employees

Google Software Engineer Interview Question

I interviewed in Urbana, IL and was asked:
"Give a string of words. Find anagram words and put them into the same list, then output the list of anagram words lists. input: [add, dad, care, race] output: [[add, dad], [care, race]]"
Add Tags [?]
Answer Flag Question

Part of a Software Engineer Interview Review - one of 2,774 Google Interview Reviews

Answers & Comments

0
of 0
votes
<?php

print_r(an(array('add','dad','race','care')));

function an($a) {
    for($i=0;$i<count($a);$i++) {
        for($j=$i+1;$j<count($a);$j++) {
            if (isan($a[$i], $a[$j])) {
                if (is_array($a[$i])) {
                    $a[$i][] = $a[$j];
                } else {
                    $a[$i] = array($a[$i], $a[$j]);
                }
                unset($a[$j]);
            }
        }
        $a = array_values($a);
    }
    return $a;
}

function isan($w1, $w2) {
    if (is_array($w1)) $w1 = $w1[0];
    if (strlen($w1) != strlen($w2)) return false;
    for($i=0;$i<count($w1);$i++) {
        $w2 = str_replace($w2, $w1[$i], '');
    }
    return (strlen($w2) == 0);
}
- sman on Nov 25, 2013 Flag Response
0
of 0
votes
l = ['add', 'dad', 'care', 'race']
dic = dict()
for w in l:
    v = ''.join(sorted(w))
    dic.setdefault(v, []).append(w)
print dic.values()
- Christian on Dec 10, 2013 Flag Response
0
of 0
votes
In Ruby

    def anagrams(arr = Array.new)
      anagrams = []
      arr.each_with_index do |w, i|
        set = w.split('').to_set
        arr.delete_at(i)
        anagram = [w]
        arr.each_with_index do |w2, j|
          next if w.length != w2.length
          if set == w2.split('').to_set
            anagram << w2
            arr.delete_at(i)
          end
        end
        anagrams << anagram if anagram.length > 1
      end
      anagrams
    end
- Shawn on Dec 12, 2013 Flag Response

To comment on this question, Sign In with Facebook or Sign Up


Tags are like keywords that help categorize interview questions that have something in common.

Glassdoor is your free inside look at Google interview questions and advice. All interview reviews posted anonymously by Google employees and interview candidates.