Google Labs Aptitude Test Questions and Answers

Ed Pegg, Jr. and Eric Weisstein

With additional contributions by
Daniel Lichtblau
Adam Strzebonski
Oyvind Tafjord
Michael Trott

Novmeber 8, 2004

Introduction

The Google Labs Aptitude Test is a set of questions exploring mathematics, computers, and creativity.  Many of the mathematical questions can be answered directly using Mathematica.  This notebook explores some of those solutions.  We leave the nonmathematical questions for actual Google applicants….

Google Aptitude Test

1. Solve this cryptic equation, realizing of course that values for M and E could be interchanged. No leading zeros are allowed.

WWWDOT - GOOGLE = DOTCOM

This can be solved through systematic application of logic.  For example, O cannot be equal to 0, since O + O + [1 or  0] = W.  That would make W == 1, but D + G == W, which is not possible.

Here is a slow brute-force method of solution that takes a few minutes on a relatively fast machine:

Off[General::"spell1"]
chars = 
        Characters /@ ToLowerCase /@ {"WWWDOT", "GOOGLE", "DOTCOM\
"};
uchars = Union[Flatten[chars]];

eqn = First[#] - Plus @@ Rest[#] &[FromDigits[#, 10] & /@ 
              chars] == 0;
Timing[
      soln = Select[Permutations[Range[0, 9]], 
          eqn /. Thread[uchars -> Most[#]] &]]

Thread[uchars -> Most[#]] & /@ soln

This gives the two solutions

777589 - 188106 == 589483
777589 - 188103 == 589486

Here is another solution using Mathematica's Reduce command:

eqn = "wwwdot" - "google" == "dotcom" /. 
          s_String :> 
            FromDigits[ToExpression[Characters[s]], 
              10];
vars = 
        Union[Cases[eqn, _Symbol, Infinity]];
ineqs = 
        And @@ (0 ≤ # ≤ 9 & /@ 
              vars);
\(\(\(eqs = 
        Outer[And, 
          Sequence @@ 
            MapThread[#1 - #2 == #3 || #1 - 1 - #2 == #3 || #1 + 
                      10 - #2 == #3 || #1 + 
                      9 - #2 == #3 &, {"wwwdot", "google", "dotcom"} /. 
                s_String :> 
                  ToExpression[Characters[s]]]];\)\(
\)
    \)\)
Select[Reduce[eqn && ineqs && #, vars, Integers] & /@ 
          eqs, (Unequal @@ vars /. ToRules[#]) =!= False &] // 
      Timing

A faster (but slightly more obscure) piece of code is the following:

cf = 
        Compile[Evaluate[{#, _Integer} & /@ {c, d, e, g, l, m, o, t, w, 
                x}], Module[
{
T = {100000, 10000, 1000, 100, 10, 1}, 
S = {100000, 10000, 
                  1000, 100, 10}, 
A, B, 
              C
}, 
A = {w, w, w, d, o, 
                  t} . T; 
B = {g, o, o, g, l} . 
                S; 
C = {d, o, t, c, o} . 
                S; 
A - B - m == C + e && 
              A - B - e == C + m]
];

Transpose[{{c, d, e, g, l, m, o, t, w}, Most[#]}] & /@ 
        Module[{perms = 
              Developer`ToPackedArray /@ 
                Take[Permutations[Range[0, 9]], All]}, 
          Select[perms, cf @@ #1 &]] // Timing

Faster still using the same approach (and requiring ~300 MB of memory):

Transpose[{{c, d, e, g, l, m, o, t, w}, 
              Most[#]}] & /@ Compile[{}, 
            Module[{perms = Take[Permutations[Range[0, 9]], All]}, 
              Select[perms, 
                Function[L, 
                  Module[{c = L[[1]], d = L[[2]], e = L[[3]], 
                      g = L[[4]], l = L[[5]], m = L[[6]], 
                      o = L[[7]], t = L[[8]], w = L[[9]], 
                      T = {100000, 10000, 1000, 100, 10, 1}, 
                      S = {100000, 10000, 1000, 100, 10}, A, B, 
                      C}, 
A = {w, w, w, d, o, t} . 
                        T; 
B = {g, o, o, g, l} . 
                        S; 
C = {d, o, t, c, o} . 
                        S; 
A - B - m == C + e && 
                      A - B - e == C + m]]]]][] // Timing

Even faster using the same approach (that does not exclude leading zeros in the solution, but that can easily be weeded out at the end):

eq = 
        Simplify["wwwdot" - "google" - "dotcom" /. 
            s_String :> 
              FromDigits[ToExpression[Characters[s]], 10]];
Join[CoefficientList[eq, #][[2]] & /@ 
        Union[Cases[eq, _Symbol, Infinity]], {0}]

Transpose[{{c, d, e, g, l, m, o, t, w}, 
              Most[#]}] & /@ Compile[{}, 
            Select[Permutations[
                Range[0, 
                  9]], {-100, -99900, -1, -100100, -10, -1, -21000, -999, 111000, 0} . # == 0 &]][] // 
      Timing

Here is an independent solution method that uses branch-and-prune techniques:

wwwdot={w,w,w,d,o,t};
google={g,o,o,g,l,e};
dotcom={d,o,t,c,o,m};
vars={w,g,d,o,t,c,l,e,m};
powersOfTen=10^Range[5,0,-1];
eqn=wwwdot.powersOfTen-google.powersOfTen==dotcom.powersOfTen;
newvars=Map[Array[#,10,0]&,vars];
vareqns=Map[#.Range[0,9]==Head[#[[1]]]&,newvars];
zeroOneConstraints=Map[0≤#≤1&,Flatten[newvars]];
noLeadingZeros=Map[#==0&,{w[0],g[0],d[0]}];
mustSumToOneConstraints=Map[Apply[Plus,#]==1&,newvars];
distinctDigits=Map[Apply[Plus,#]≤1&,Transpose[newvars]];
allInfo=Flatten[{eqn,vareqns,zeroOneConstraints,noLeadingZeros,mustSumToOneConstraints,distinctDigits}];

\(\(Developer`SetSystemOptions["LinearProgrammingOptions" -> {"InteriorPointSize" -> 1, "Preprocessing" -> 
              True}];\)\)

Off[General::"spell1"]

wwwdotgoogledotcom[constraints_, vars_, zeroOneVars_] := 
      Module[{allvars = Join[vars, zeroOneVars], program = constraints, 
          solns = {}, stack = {constraints, {}}, soln, soln01, badpos, 
          extra}, stack = {program, {}}; 
While[
          stack =!= {}, program = stack[[1]]; 
          stack = stack[[2]]; 
Internal`DeactivateMessages[
            soln = NMinimize[{1, program}, 
                allvars]]; 
If[! FreeQ[soln, 
                Indeterminate], Continue[]]; 
soln = 
            Chop[soln[[2]], 10^(-8)]; 
soln01 = 
            zeroOneVars /. soln; 
badpos = 
            Position[
              soln01, (aa_ /; 
                  Chop[aa - Round[aa], 10^(-8)] =!= 0), {1}, 1, 
              Heads -> False]; 
If[badpos == {}, 
            soln = Thread[{(vars /. soln) /. 
                    aa_?NumberQ :> Round[aa], 
                  vars}]; 
solns = 
              Append[solns, soln]; 
Do[
              extra = Map[#[[1]] == #[[2]] &, 
                  Drop[soln, j]]; 
extra = 
                Append[extra, soln[[j, 2]][soln[[j, 1]]] == 
                    0]; 
stack = {Join[program, extra], 
                  stack};, {j, Length[vars], 
                1, -1}]; 
Continue[],  (*else*) 
              badpos = 
              badpos[[1, 1]]; 
stack = {Append[program, 
                  zeroOneVars[[badpos]] == 0], 
                stack}; 
stack = {Append[program, 
                  zeroOneVars[[badpos]] == 1], 
                stack};];]; 
Sort /@ 
          Map[Reverse, solns, {2}]
]

wwwdotgoogledotcom[allInfo, vars, Flatten[newvars]] // 
      Timing

And the winner for overall fastest:

enforceUniqueDigits[l_,k_]:=If[Length[Union[Take[l,-k]]]=!=k,Sequence@@{},l]

T[k_]:=T[k]=Table[10^j,{j,k-1,0,-1}];

dotcom[{w_,d_,g_,c_,l_,o_,t_,e_,m_},k_]:=Take[{d,o,t,c,o,m},-k].T[k]
google[{w_,d_,g_,c_,l_,o_,t_,e_,m_},k_]:=Take[{g,o,o,g,l,e},-k].T[k]
wwwdot[{w_,d_,g_,c_,l_,o_,t_,e_,m_},k_]:=Take[{w,w,w,d,o,t},-k].T[k]

addDigit[L:{w_,d_,g_,c_,l_,o_,t_,e_,m_},x_]:=IntegerDigits[dotcom[L,x]+google[L,x],10,x][[1]]

insertDigit[L_,p_]:=enforceUniqueDigits[#,p]&/@Flatten[Function[s,Table[MapAt[k&,s,-p],{k,0,9}]]/@L,1];

(em=enforceUniqueDigits[#,2]&/@(Flatten[Table[{0,0,0,0,0,0,0,e,m},{m,0,9},{e,0,9}],1]);
tem=enforceUniqueDigits[#,3]&/@Function[s,MapAt[addDigit[s,1]&,s,-3]]/@em;
otem=insertDigit[tem,4];
lotem=insertDigit[otem,5];
lotem=Select[lotem,#[[-4]]==addDigit[#,2]&];
clotem=insertDigit[lotem,6];
gclotem=insertDigit[clotem,7];
dgclotem=enforceUniqueDigits[#,8]&/@Function[s,MapAt[addDigit[s,3]&,s,2]]/@gclotem;
dgclotem=enforceUniqueDigits[#,9]&/@Function[s,MapAt[addDigit[s,4]&,s,1]]/@dgclotem;
Sort[Thread[{w,d,g,c,l,o,t,e,m}->#]]&/@
Select[dgclotem,dotcom[#,6]+google[#,6]==wwwdot[#,6]&])//Timing

2. Write a haiku describing possible methods for predicting search traffic seasonality.

MathWorld's search engine
seemed slowed this May. Undergrads
prepping for finals.

3.       1
         1 1
         2 1
      1 2 1 1
   1 1 1 2 2 1

 What's the next line?

312211.  This is the “look and say” sequence in which each term after the first describes the previous term: one 1 (11); two 1s (21); one 2 and one 1 (1211); one 1, one 2, and two 1's (111221); and so on.  See the look and say sequence entry on MathWorld for a complete write-up and the algebraic form of a fascinating related quantity known as Conway's constant.

RunLengthEncode[x_List] := (Through[{First, Length}[#1]] &) /@ 
        Split[x]
LookAndSay[n_, d_:  1] := 
      NestList[Flatten[Reverse /@ RunLengthEncode[#]] &, {d}, 
        n - 1]

FromDigits /@ LookAndSay[6]

4. You are in a maze of twisty little passages, all alike.  There is a dusty laptop here with a weak wireless connection.  There are dull, lifeless gnomes strolling around.  What dost thou do?

    A) Wander aimlessly, bumping into obstacles until you are eaten by a grue.
    B) Use the laptop as a digging device to tunnel to the next level.
    C) Play MPoRPG until the battery dies along with your hopes.
    D) Use the computer to map the nodes of the maze and discover an exit path.
    E) Email your resume to Google, tell the lead gnome you quit and find yourself in whole different world [sic].

In general, make a state diagram.  However, this method would not work in certain pathological cases such as, say, a fractal maze.  For an example of this and commentary, see Ed Pegg's column about state diagrams and mazes.

5. What's broken with Unix?

Their reproductive capabilities.

How would you fix it?

[This exercise is left to the reader.]

6. On your first day at Google, you discover that your cubicle mate wrote the textbook you used as a primary resource in your first year of graduate school. Do you:

    A) Fawn obsequiously and ask if you can have an autograph.
    B) Sit perfectly still and use only soft keystrokes to avoid disturbing her concentration
    C) Leave her daily offerings of granola and English toffee from the food bins.
    D) Quote your favorite formula from the textbook and explain how it's now your mantra.
    E) Show her how example 17b could have been solved with 34 fewer lines of code.

[This exercise is left to the reader.]

7. Which of the following expresses Google's over-arching philosophy?

    A) "I'm feeling lucky"
    B) "Don't be evil"
    C) "Oh, I already fixed that"
    D) "You should never be more than 50 feet from food"
    E) All of the above

[This exercise is left to the reader.]

8. How many different ways can you color an icosahedron with one of three colors on each face?

For an asymmetric 20-sided solid, there are (3^20) possible 3-colorings.  For a symmetric 20-sided object, the Pólya enumeration theorem can be used to obtain the number of distinct colorings.  Here is a concise Mathematica implementation:

Off[General::"shdw", General::"spell1"]
<< DiscreteMath`Combinatorica`
\(<< Graphics`Polyhedra`
\)
cycleit[l_] := 
      RotateLeft[l, Ordering[l][[1]] - 1]; 
ColorMySolid[solid_, colors_] := 
      Module[
{f = cycleit /@ Faces[solid], GroupIh, 
          GroupI, GroupFaces}, 
GroupIh = 
          Automorphisms[
            FromUnorderedPairs[
              Union[Sort /@ 
                  Flatten[Partition[#, 2, 1, 1] & /@ f, 
                    1]]]]; 
GroupI = 
          Select[GroupIh, 
            MemberQ[f, 
                cycleit[#[[f[[1]]]]]] &]; 
GroupFaces = 
          KSubsetGroup[GroupI, Sort /@ f]; 
Polya[
          GroupFaces, colors]
]

ColorMySolid[Icosahedron, colors]

% /. colors ->  3

What colors would you choose?

[This exercise is left to the reader.]

9. This space left intentionally blank.  Please fill it with something that improves upon emptiness.

For nearly 10,000 images of mathematical functions, see The Wolfram Functions Site visualization gallery.

10. On an infinite, two-dimensional, rectangular lattice of 1-ohm resistors, what is the resistance between two nodes that are a knight's move away?

R[m_, n_] := 
      (1/(2  π)) Integrate[(1/t) (1 - (((((t - I)/(t + I))))^(m + n)) (((((t - 1)/(t + 1))))^Abs)[m - n]), {t, 
            0, ∞}]

R[1, 2]

This problem is discussed in J. Cserti's 1999 arXiv preprint.  It is also discussed in The Mathematica GuideBook for Symbolics, the forthcoming fourth volume in Michael Trott's GuideBook series, the first two of which were published just last week by Springer-Verlag.  The contents for all four GuideBooks, including the two not yet published, are available on the DVD distributed with the first two GuideBooks.

11. It's 2PM on a sunny Sunday afternoon in the Bay Area.  You're minutes from the Pacific Ocean, redwood forest hiking trails and world class cultural attractions.  What do you do?

[This exercise is left to the reader.]

12. In your opinion, what is the most beautiful math equation ever derived?

There are obviously many candidates.  The following list gives ten of the authors' favorites:

1. Archimedes' recurrence formula: \(TraditionalForm\`a\_\(2\ n\) = \(2\ a\_n\ b\_n\)\/\(a\_n + b\_n\)\), (Subscript[b, 2 n]) = (Sqrt[(Subscript[a, 2 n]) (Subscript[b, n])]), (Subscript[a, n]) > π > (Subscript[b, n]), (Subscript[a, ∞]) = (Subscript[b, ∞])
2. Euler formula: (e^(i π)) + 
          1 == 0
3. Euler-Mascheroni constant: \(lim\+\(k -> ∞\) \((∑\+\(n = 1\)\%k 1\/n - log(k))\)\)==ℽ
4. Riemann hypothesis: \(TraditionalForm\`ζ\ \((α + β\ i)\) == 0\) and β ≠ 0 implies α == (1/2)
5. Gaussian integral:   \(TraditionalForm\`∫\_\(-∞\)\%∞\( e\^\(-x\^2\)\) dx == \@π\)
6. Ramanujan's prime product formula: (∏_(k = 1)^∞)((((Subscript[p, k])^2)+1)/(((Subscript[p, k])^2)-1))==(5/2)
7. Zeta-regularized product: (∏_(k = 1)^∞) 
          k == (Sqrt[2 π])
8. Mandelbrot set recursion: (Subscript[z, n + 1]) == (Subscript[z, n]^2) + C
9. BBP formula: \(TraditionalForm\`π == ∑\+\(n = 0\)\%∞\((\(-\(2\/\(8\ n + 4\)\)\) - 1\/\(8\ n + 5\) - 
                1\/\(8\ n + 6\) + 4\/\(8\ n + 1\))\)\ \((1\/16)\)\^n\)
10. Cauchy integral formula: \(TraditionalForm\`f(
          z\_0) == \(1\/\(2\ π\ i\)\) \(∮\(\(f(z)\)\/\(z - z\_0\)\) dz\)\)

An excellent paper discussing the most beautiful equations in physics is Daniel Z. Freedman's “Some beautiful equations of mathematical physics.”  Note that the physics view on beauty in equations is less uniform than the mathematical one.  To quote the not-necessarily-standard view of theoretical physicist P.A.M. Dirac, “It is more important to have beauty in one's equations than to have them fit experiment.”

13. Which of the following is NOT an actual interest group formed by Google employees?

    A. Women's basketball
    B. Buffy fans
    C. Cricketeers
    D. Nobel winners
    E. Wine club

[This exercise is left to the reader.]

14. What will be the next great improvement in search technology?

Semantic searching of mathematical formulas.  See http://functions.wolfram.com/About/ourvision.html for work currently underway at Wolfram Research that will be made available in the near future.

15. What is the optimal size of a project team, above which additional members do not contribute productivity equivalent to the percentage increase in the staff size?

    A) 1
    B) 3
    C) 5
    D) 11
    E) 24

[This exercise is left to the reader.]

16. Given a triangle ABC, how would you use only a compass and straight edge to find a point P such that triangles ABP, ACP and BCP have equal perimeters?  (Assume that ABC is constructed so that a solution does exist.)

This is the isoperimetric point, which is at the center of the larger Soddy circle. It is related to Apollonius' problem. The three tangent circles are easy to construct: The circle around C has diameter a + b - c, which gives the other two circles.  A summary of compass and straightedge constructions for the outer Soddy circle can be found in “Apollonius' Problem: A Study of Solutions and Their Connections” by David Gisch and Jason M. Ribando.

17. Consider a function which, for a given whole number n, returns the number of ones required when writing out all numbers between 0 and n.  For example, f(13)=6.  Notice that f(1)=1.  What is the next largest n such that f(n)=n?

The following Mathematica code computes the difference between [the cumulative number of 1s in the positive integers up to n] and [the value of n itself] as n ranges from 1 to 500,000:

data = 
        MapIndexed[#1 - #2[[1]] &, 
          Rest[FoldList[Plus, 0, 
              Table[DigitCount[n, 10, 1], {n, 500000}]]]];

<< Graphics`Colors`
ListPlot[
        Take[MapIndexed[{#2[[1]], #1} &, data], {1, -1, 
            1000}], 
PlotStyle -> Red];

The solution to the problem is then the first position greater than the first at which data equals 0:

Position[data, 0] // Flatten

which are the first few terms of sequence A014778 in the On-Line Encyclopedia of Integer Sequences.

Checking by hand confirms that the numbers from 1 to 199981 contain a total of 199981 1s:

IntegerDigits /@ Range[199981] // Flatten // 
      Count[#, 1] &

18.  What is the coolest hack you've ever written?

While there is no “correct” answer, a nice hack for solving the first problem in the SIAM hundred-dollar, hundred-digit challenge can be achieved by converting the limit into the strongly divergent series:

Sum[(((-1))^k) (((2  k))^(2  k - 1)), {k, ∞}]

and then using Mathematica's numerical function SequenceLimit to trivially get the correct answer (to six digits),

Off[SequenceLimit::"seqlim"]
SequenceLimit[
      FoldList[Plus, 
        0, N[#, 1000] &@
          Table[-(((-1))^k) (((2  k))^(2  k - 1)), {k, 300}]], 
      WynnDegree -> 20]

You must tweak parameters a bit or write your own sequence limit to get all 10 digits.

[Other hacks are left to the reader.]

19. 'Tis known in refined company, that choosing K things out of N can be done in ways as many as choosing N minus K from N: I pick K, you the remaining.

This simply states the binomial coefficient identity (({{N}, {K}}))==(({{N}, {N-K}})).

In other words, for positive integers n and k≤n/2, find a bijection f between k-element subsets of [n]={1,…,n} and (n-k)-element subsets of [n] such that if J=f (i) then the subset J contains I.

One solution is as follows. Represent a subset I in [n] by a binary sequence with k 1's and (n-k) 0's (1 in the ith place means that i is in I). If the sequence contains a fragment 1, 0 then cross it out and keep repeating this procedure until we have no fragments 1, 0 left. The remaining sequence has the form 0, …, 0, 1, …, 1 (r 0's followed by s 1's).

We have r≥s because we assume that k≤n/2. Transform this sequence into the sequence of s 0's followed by r 1's and then insert all digits that we crossed out into their original positions. We obtain a binary sequence with (n-k) 1's and k 0's. This sequence represents the (n-k) -element subset J that contains i. This construction is inversable, thus the map I→J is a bijection (A. Postnikov, pers. comm., Apr. 13, 2005).

Find though a cooler bijection, where you show a knack uncanny, of making your choices contain all K of mine.  Oh, for pedantry: let K be no more than half N.

'Tis more problematic to disentangle semantic meaning precise from the this paragraph of verbiage peculiar.

20. What number comes next in the sequence: 10, 9, 60, 90, 70, 66, ?

    A) 96
    B) 1000000000000000000000000000000000\
         0000000000000000000000000000000000\
         000000000000000000000000000000000
    C) Either of the above
    D) None of the above

This can be looked up and found to be sequence A052196 in the On-Line Encyclopedia of Integer Sequences, which gives the largest positive integer whose English name has n letters.  For example, the first few terms are ten, nine, sixty, ninety, seventy, sixty-six, ninety-six, ….  A more correct sequence might be ten, nine, sixty, googol, seventy, sixty-six, ninety-six, googolplex, ….  And also note, incidentally, that the correct spelling of the mathematical term “googol” differs from the name of the company that made up this aptitude test.

The first few can be computed using the NumberName function in Eric Weisstein's MathWorld packages:

<< MathWorld`IntegerSequences`

\(pairs = 
      Last /@ Split[
          Sort[\({StringLength[
                    StringReplace[
                      NumberName[#], {" " -> "", "-" -> ""}]], #} &\) /@ Range[100]], #1[\([1]\)] == #2[\([1]\)] &]\)

Last /@ Take[pairs, 7]

A mathematical solution could also be found by fitting a Lagrange interpolating polynomial to the six known terms and extrapolating:

pts = {10, 9, 60, 90, 70, 66};

newpts = 
      Function[x, Evaluate[InterpolatingPolynomial[pts, x]]] /@ 
        Range[7]

Plot[Evaluate[InterpolatingPolynomial[pts, x]], {x, 0, 7}, 
        PlotStyle -> Red, 
        Epilog -> {Red, PointSize[ .02], 
            Point /@ Transpose[{Range[7], newpts}]}];

21. In 29 words or fewer, describe what you would strive to accomplish if you worked at Google Labs.

[This exercise is left to the reader.]